标签:
Sort a linked list in O(n log n) time using constant space complexity.
class Solution { public: ListNode *sortList(ListNode *head) { if(!head || !head->next ) return head; return quickSort(head)[0]; } vector< ListNode* > quickSort(ListNode *head){ vector< ListNode* > ret; if(!head->next) { ret.push_back(head); ret.push_back(head); return ret; } ListNode* headSmaller = NULL; ListNode* headGreater = NULL; ListNode* current = head->next; ListNode* prev = head; ListNode* tmp; while(current){ if(current->val > head->val){ prev->next = current->next; if(!headGreater){ headGreater = current; headGreater->next = NULL; } else{ current->next = headGreater->next; headGreater->next = current; } current = prev->next; } else if(current->val < head->val){ prev->next = current->next; if(!headSmaller){ headSmaller = current; headSmaller->next = NULL; } else{ current->next = headSmaller->next; headSmaller->next = current; } current = prev->next; } else { prev = current; current = current->next; } } vector< ListNode* > retGreater; vector< ListNode* > retSmaller; if(headSmaller) { retSmaller = quickSort(headSmaller); retSmaller[1]->next = head; ret.push_back(retSmaller[0]); } else ret.push_back(head); if(headGreater){ retGreater = quickSort(headGreater); prev->next = retGreater[0]; ret.push_back(retGreater[1]); } else ret.push_back(prev); return ret; } };
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4853068.html