148. Sort list (Java for single-linked list)

Source: Internet
Author: User

Title: Sort a linked list in O(n log n) time using constant space complexity.

Analysis: to order the single-linked list, the time complexity required is O (NLOGN), the space complexity is O (1). The sorting algorithm with time complexity O (NLOGN) has a quick sort and merge sort,

However, for a single-linked list, the exchange between elements is more complicated, but it is relatively simple to connect two ordered linked lists, so the idea of merging sort is used here.

Coding:

 PublicListNode sortlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL)            returnHead; //find the middle node of the list, a slow two pointerListNode fast =Head; ListNode Slow=Head; ListNode Pre=NULL;//record the last node of the first section//divide a single linked list into two parts         while(Fast! =NULL&& Fast.next! =NULL) {Fast=Fast.next.next; Pre=slow; Slow=Slow.next; }                //split the two sections open        if(Pre! =NULL) Pre.next=NULL; //recursive ordering of two parts separatelyListNode L1 =Sortlist (head); ListNode L2=sortlist (slow); returnMerge (L1,L2);//Merge            }        //merge two ordered sequences     Publiclistnode Merge (ListNode L1,listnode L2) {if(L1 = =NULL)           returnL2; if(L2 = =NULL)           returnL1; ListNode l=NewListNode (-1); ListNode Newhead=l;  while(L1! =NULL&& L2! =NULL){             if(L1.val <l2.val) {Newhead.next=L1;//The use of a single-linked list of properties, no additional space, so that the space complexity of O (1) L1=L1.next; Newhead=Newhead.next; } Else{Newhead.next=L2; L2=L2.next; Newhead=Newhead.next; }        }                if(L1! =NULL) Newhead.next=L1; if(L2! =NULL) Newhead.next=L2; returnL.next; }

148. Sort list (Java for single-linked 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.