首页 > 代码库 > Sort List && Insertion Sort List (链表排序总结)

Sort List && Insertion Sort List (链表排序总结)

Sort List

          

Sort a linked list in O(n log n) time using constant space complexity.

 

说明:归并排序: 时间 O(nlogn),空间 O(1). 每次将链表一分为二, 然后再合并。快排(用两个指针)
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ ListNode* getMid(ListNode *head) {    ListNode *first, *second, *preFirst;    preFirst = first = second = head;    while(second != NULL) {        preFirst = first;        first = first->next;        if(second->next == NULL) break;        second = second->next->next;    }    preFirst->next = NULL;    return first;}void Merge(ListNode *head1, ListNode *head2) {    if(head1->val > head2->val) {		int tem = head1->val;		head1->val = head2->val;		head2->val = tem;	}    ListNode *p = head1;    while(p->next != NULL && head2 != NULL) {        if(p->next->val >= head2->val) {            ListNode *q = p->next;            p->next = head2;            head2 = head2->next;            p->next->next = q;            p = p->next;        } else {            p = p->next;        }    }    if(head2 != NULL)        p->next = head2;} void MergeSort(ListNode *head) {    if(head == NULL || head->next == NULL) return;    ListNode *mid = getMid(head);	MergeSort(head);	MergeSort(mid);    Merge(head, mid);} class Solution {public:    ListNode *sortList(ListNode *head) {       MergeSort(head);       return head;    }};

 

Insertion Sort List

          

Sort a linked list using insertion sort.

说明: 与顺序表不同的时,每次找插入位置时从头开始走。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *insertionSortList(ListNode *head) {        ListNode *p, *q;        for(q = head; q != NULL; q = q->next) {            for(p = head; p != q; p = p->next) {                if(p->val >= q->val) {                    int tem = p->val;                    p->val = q->val;                    q->val = tem;                }            }        }        return head;    }};