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 *getMid(ListNode* head){ if(head==NULL || head->next==NULL)return head; ListNode*prev=NULL; ListNode*p1=head; ListNode*p2=head; while(p2){ prev=p1; p1=p1->next; p2=p2->next; if(p2)p2=p2->next; } prev->next=NULL; return p1; } ListNode *sortList(ListNode *head) { // nlogn的复杂度,用归并排序求解 if(head==NULL || head->next==NULL)return head; //原列表平分为两个列表 ListNode*head1=head; ListNode*head2=getMid(head); //分别对两个列表进行排序 ListNode*p1=sortList(head1); ListNode*p2=sortList(head2); ListNode*newhead=NULL; ListNode*p=NULL; //归并 while(p1&&p2){ if(p1->val<p2->val){ if(p==NULL)newhead=p1; else p->next=p1; p=p1; p1=p1->next; } else{ if(p==NULL) newhead=p2; else p->next=p2; p=p2; p2=p2->next; } } if(p1) p->next=p1; if(p2) p->next=p2; return newhead; } };
LeetCode: Sort List [148],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/36204355