Sort List leetcode

Source: Internet
Author: User

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


Related Article

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.