[leetcode]148. Sort list Linked list merge sorting

Source: Internet
Author: User

Requires time complexity O (NLOGN), Spatial complexity O (1), with merge sort

The traditional merge sort space complexity is O (n), the reason is to use an array to represent the merged array, but here with the linked list to represent the chain list of ordered linked list, because the link table space complexity is O (1), so can.

Linked list problems often appear tle problem or mle problem, this time to check the link list splicing process or cycle process, see if there is a dead loop

 PublicListNode sortlist (ListNode head) {if(head==NULL|| head.next==NULL)returnHead; //use the fast pointer to find the midpoint of the list and divide it into two parts recursively//to set a forward node record a slow pointer to the previous node as the end of the previous sectionListNode slow = Head,fast = Head,pre =NULL;  while(fast!=NULL&&fast.next!=NULL) {Pre=slow; Slow=Slow.next; Fast=Fast.next.next; }        //first half partPre.next =NULL; ListNode L1=Sortlist (head); ListNode L2=sortlist (slow); returnmerge (L1,L2); }     Publiclistnode Merge (ListNode L1,listnode L2) {//set up ahead nodeListNode pre =NewListNode (0), temp =Pre;  while(l1!=NULL&&l2!=NULL)        {            if(l1.val<l2.val) {Temp.next=L1; L1=L1.next; }            Else{Temp.next=L2; L2=L2.next; } temp=Temp.next; }        if(l1!=NULL) Temp.next =L1; if(l2!=NULL) Temp.next =L2; returnPre.next; }

Merge sort See: Http://www.cnblogs.com/stAr-1/p/8445377.html

[leetcode]148. Sort list Linked list merge sorting

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.