标签:
Sort a linked list in O(n log n) time using constant space complexity.
常见排序方法有很多,插入排序,选择排序,堆排序,快速排序,冒泡排序,归并排序,桶排序等等。。它们的时间复杂度不尽相同,而这里题目限定了时间必须为O(nlgn),符合要求只有快速排序,归并排序,堆排序,而根据单链表的特点,最适于用归并排序。代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *sortList(ListNode *head) { if (!head || !head->next) return head; ListNode *fast = head, *slow = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } fast = slow; slow = slow->next; fast->next = NULL; fast = sortList(head); slow = sortList(slow); return merge(fast, slow); } ListNode *merge(ListNode *head1, ListNode *head2) { ListNode *res = new ListNode(-1); ListNode *cur = res; while (head1 && head2) { if (head1->val < head2->val) { cur->next = head1; head1 = head1->next; } else { cur->next = head2; head2 = head2->next; } cur = cur->next; } if (head1) cur->next = head1; if (head2) cur->next = head2; return res->next; } };
标签:
原文地址:http://www.cnblogs.com/grandyang/p/4249905.html