题目:
Sort a linked list in O(n log n) time using constant space complexity.
代码思想参考http://blog.youkuaiyun.com/xudli/article/details/16819545
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* 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) {
return mergeSort(head);
}
private:
ListNode *mergeSort(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *slow = head, *fast = head;
ListNode *pre_slow = head;
//分治法:使用快慢指针进行分组,slow之前为一组,之后为一组;
while(fast != NULL && fast->next != NULL) {
fast = fast->next->next;
pre_slow = slow;
slow = slow->next;
}
pre_slow->next = NULL;
ListNode *h1 = mergeSort(head);
ListNode *h2 = mergeSort(slow);
return merge(h1, h2);
}
ListNode *merge(ListNode *h1, ListNode *h2) {
ListNode *dummy = new ListNode(-1);
ListNode *cur = dummy;
if(h1 == NULL && h2 == NULL)
return NULL;
while(h1 != NULL && h2 != NULL) {
if(h1->val <= h2->val) {
cur->next = h1;
h1 = h1->next;
}
else {
cur->next = h2;
h2 = h2->next;
}
cur = cur->next;
}
//链表h1还有剩余
while(h1 != NULL) {
cur->next = h1;
h1 = h1->next;
cur = cur->next;
}
//链表h2有剩余
while(h2 != NULL) {
cur->next = h2;
h2 = h2->next;
cur = cur->next;
}
cur = dummy->next;
delete dummy;
return cur;
}
};