首页 > 代码库 > 148. Sort List
148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
用mergeSort.快排的时间复杂度最差是n^2;
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeList(ListNode *head1,ListNode *head2){ if(!head1)return head2; if(!head2)return head1; ListNode * res = new ListNode(-1); ListNode * tmp = res; ListNode * p = head1; ListNode * q = head2; while(p && q){ if(p->val<=q->val){ tmp->next = p; tmp = p; p = p->next; }else{ tmp->next = q; tmp = q; q = q->next; } } if(p) tmp->next = p; if(q) tmp->next = q; return res->next; } ListNode* sortList(ListNode* head) { if(!head || !head->next){ return head; } ListNode *pSlow = head; ListNode *pFast = head; while(pFast->next && pFast->next->next){ pFast = pFast->next->next; pSlow = pSlow->next; } ListNode *head2= pSlow->next; pSlow->next = NULL; ListNode *head1= head; head1 = sortList(head1); head2 = sortList(head2); return mergeList(head1,head2); } };
148. Sort List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。