Implementation of single-link table sequencing time complexity requirements for NLOGN
Because it is a single-linked list, with a quick sort can not go to the front (the two-way list is considered), here we use the merge sort
The code is as follows:
<span style= "FONT-SIZE:18PX;" >/** * 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) {if (head==null| | Head->next==null) return head; ListNode *onestep=head; ListNode *twostep=head;//defines two pointers, one step, one walk two steps, to find the middle node//ListNode *first=null; ListNode *second=null; while (twostep->next!=null&&twostep->next->next!=null) {onestep=onestep->next; twostep=twostep->next->next; }//At this time OneStep point to the entire list of the middle, if even so both sides of the balance, if it is odd, pointing in the middle need to onestep out from the Twostep=onestep; onestep=onestep->next;//at this point the onestep points to the second half twostep->next=null;//separating the first and second halves Twostep=sort List (head); Onestep=sortlist (OneStep); Return Meger (twostep,onestep); } ListNode *meger (ListNode *first,listnode *second) {ListNode *result; ListNode *p; if (First==null) return second; if (second==null) return first; Initializes the result if (first->val<second->val) {result=first; first=first->next; } else {Result=second; second=second->next; } P=result; while (First!=null&&second!=null) {if (first->val<second->val) { p->next=first; first=first->next; } else {p->next=second; second=second->next; } p=p->next; } if (First!=null) p->next=first; else if (second!=null) p->next=second; return result; }};</span>
Sort List Leetcode