Leetcode -- Sort List
Problem Description:
Sort a linked list in O (n log n) time using constant space complexity.
Analysis: sort the linked list. When the time complexity of the Sorting Algorithm is O (nlogn), only merge, fast sort, and Heap Sort are considered. It is more appropriate to apply the merge to the linked list, here, we use the speed pointer to find the intermediate node of the linked list, and sort the order for Recursive merge on both sides, and then merge the two sides to obtain the final ordered sequence. 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 |! Head-> next) return head; ListNode * p = head, * q = head, * r = NULL, * newhead = NULL; while (q & q-> next! = NULL) {r = p; p = p-> next; q = q-> next;} q = r-> next; // locate the Start Node r-> next = NULL; p = head; p = sortList (p); q = sortList (q); if (p & q) {if (p-> val <= q-> val) // initialize the header node {newhead = r = p; p = p-> next ;} else {newhead = r = q; q = q-> next;} // merge p and q while (p & q) {if (p-> val <= q-> val) {r-> next = p; r = p; p = p-> next ;} else {r-> next = q; r = q; q = q-> next ;}} if (p) r-> next = p; if (q) r-> next = q; return newhead ;}};