Sort List leetcode
The time complexity of sorting a single-chain table must be nlogn.
Because it is a single-chain table, you cannot traverse the table before using quick sorting (two-way linked list can be considered). Here we use Merge Sorting.
The Code is as follows:
/*** 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 for one step and the other for finding the intermediate node/ListNode * first = NULL; // ListNode * second = NULL; while (twostep-> next! = NULL & twostep-> next! = NULL) {onestep = onestep-> next; twostep = twostep-> next;} // at this time, onestep points to the middle of the entire linked list. If the number is even, both sides are balanced, if it is an odd number, twostep = onestep must be separated from onestep to the center; onestep = onestep-> next; // at this time, onestep points to the second half of twostep-> next = NULL; // separate the first half and the second half. twostep = sortList (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; // initialize result if (first-> val
Val) {result = first; first = first-> next;} else {result = second; second = second-> next;} p = result; while (first! = NULL & second! = NULL) {if (first-> val
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 ;}};