leetcode: sort list

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

====analysis=======

mergeSort for singly-linked list 

====code=======

 
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeSort(ListNode *head, ListNode *newhead) {
if(!head) return newhead;
if(!newhead) return head;

ListNode *smaller = head->val <= newhead->val ? head : newhead;
ListNode *larger = head->val > newhead->val ? head : newhead;
ListNode *result = smaller;

while(smaller->next && larger) {
if(smaller->val <= larger->val && larger->val < smaller->next->val) {

ListNode *q = larger->next;
larger->next = smaller->next;
smaller->next = larger;

smaller = smaller->next;
larger = q;
} else {
smaller = smaller->next;
}
}

if(larger) {
smaller->next = larger;
}

return result;
}
ListNode *sortList(ListNode *head) {
if(!head || !head->next) return head;
ListNode *slow = head;
ListNode *fast = head->next;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}

ListNode *rightP = slow->next;
slow->next = NULL;
head = sortList(head);
rightP = sortList(rightP);

return mergeSort(head, rightP);
}
};

 

你可能感兴趣的:(Algorithm,linked list,sort)