首页 > 代码库 > Sort List
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
/** * 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) { ListNode* left; ListNode* right; quicksort(head,left,right); return left; } void quicksort(ListNode* head,ListNode*& left,ListNode*& right) { if(head==NULL) { left=NULL;right=NULL; return; } if(head->next==NULL) { left=head; right=head; return; } ListNode* headsmall=NULL; ListNode* smallp; ListNode* pre=head; ListNode* p=head->next; int val=head->val; bool issame=true; while(p!=NULL) { while(p!=NULL) { if(p->val!=val) issame=false; if(p->val<val) break; pre=p; p=p->next; } if(p!=NULL) { pre->next=p->next; if(headsmall==NULL) { headsmall=p; } else { smallp->next=p; } smallp=p; p=p->next; smallp->next=NULL; } } //all the same if(issame && headsmall==NULL) { left=head; right=pre; return; } ListNode* headbig=head->next; head->next=NULL; ListNode* bigleft; ListNode* bigright; ListNode* smallleft; ListNode* smallright; if(headsmall!=NULL && headbig!=NULL) { quicksort(headbig,bigleft,bigright); quicksort(headsmall,smallleft,smallright); smallright->next=head; head->next=bigleft; left=smallleft; right=bigright; } else if(headsmall==NULL) { quicksort(headbig,bigleft,bigright); head->next=bigleft; left=head; right=bigright; } else if(headbig==NULL) { quicksort(headsmall,smallleft,smallright); smallright->next=head; left=smallleft; right=head; } } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。