Sort a linked list in O(n log n) time using constant space complexity.
Code:
class Solution { public: ListNode *sortList(ListNode *head) { if(!head) return head; map<int,vector<ListNode *>> sortMap; vector<int> sortVector; ListNode *anchor=new ListNode(0); anchor->next=head; ListNode *cur=head; int n=0; ///////////////// put into map and vector ///////////////// while(cur){ n++; vector<ListNode *> sameValue; sortVector.push_back(cur->val); sortMap[cur->val].push_back(cur); cur=cur->next; } sort(sortVector.begin(),sortVector.end()); // quick-sort costs O(nlogn) ///////////////// reconstruct ///////////////// anchor->next=sortMap[sortVector[0]].front(); for(int j=1,len=sortMap[sortVector[0]].size();j<len;j++) sortMap[sortVector[0]][j-1]->next=sortMap[sortVector[0]][j]; for(int i=1;i<n;i++){ if(sortVector[i-1]!=sortVector[i]){ sortMap[sortVector[i-1]].back()->next=sortMap[sortVector[i]].front(); sortMap.erase(sortVector[i-1]); for(int j=1,len=sortMap[sortVector[i]].size();j<len;j++) sortMap[sortVector[i]][j-1]->next=sortMap[sortVector[i]][j]; } } sortMap[sortVector[n-1]].back()->next=NULL; sortMap.erase(sortVector[n-1]); ////////////////////////////////////////////// head=anchor->next; delete anchor; return head; } };