Sort a linked list in the time of O (nlogn .. It is obvious to use merge or quick sort.
The first time I knew that the original merger could also be written using a linked list, I was brushed down to three views ..... Use the speed pointer method to find the demarcation point.
/** * 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){ListNode *slow=head;ListNode *fast=head;while(fast->next!=NULL&&fast->next->next!=NULL){slow=slow->next;fast=fast->next;fast=fast->next;}return slow;} ListNode *sortList(ListNode *head) { if(head==NULL||head->next==NULL) { return head; } ListNode *mid=getMid(head); ListNode *next=mid->next; mid->next=NULL; return mergeList(sortList(head),sortList(next)); } ListNode *mergeList(ListNode *a,ListNode *b) { ListNode *tmphead=new ListNode(-1); ListNode *cur=tmphead; while(a&&b) { if(a->val<=b->val) { cur->next=a; a=a->next; } else { cur->next=b; b=b->next; } cur=cur->next; } cur->next=NULL; cur->next= a==NULL?b:a; cur=tmphead->next; delete tmphead; return cur; }};