标签:style blog os io for ar cti div
Sort a linked list in O(n log n) time using constant space complexity.
/** * 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; } };
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; } };
Sort List && Insertion Sort List (链表排序总结),布布扣,bubuko.com
Sort List && Insertion Sort List (链表排序总结)
标签:style blog os io for ar cti div
原文地址:http://www.cnblogs.com/liyangguang1988/p/3902268.html