Leetcode -- Sort List

Source: Internet
Author: User

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 ;}};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.