148. Sort List

Source: Internet
Author: User

Method 1: Merge Sorting ideas:

(1) Design a function to find the middle node, (2) design a merging of two already ordered functions; (3) the main function;

One of the first function thought: is in 109 to convert into BST in the same way, but also the speed of the list to solve the ring list of the design of the same idea!

 Public classSolution {PrivateListNode Findmidnode (ListNode head) {ListNode slow=Head; ListNode Fast=Head;  while(Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; }        returnslow; }    Privatelistnode Merge (ListNode head1, ListNode head2) {ListNode dummy=NewListNode (0); ListNode Index=dummy;  while(Head1! =NULL&& head2! =NULL)        {            if(Head1.val <head2.val) {Index.next=Head1; Head1=Head1.next; }             Else{Index.next=head2; Head2=Head2.next; } Index=Index.next; }        if(Head1! =NULL) Index.next =Head1; ElseIndex.next =head2; returnDummy.next; }     PublicListNode sortlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL){            returnHead; } ListNode Mid=Findmidnode (head); ListNode Left=sortlist (Mid.next); Mid.next=NULL; ListNode Right=Sortlist (head); returnmerge (Left,right); }}

148. Sort List

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.