"Leetcode" Sort list Solution

Source: Internet
Author: User

First, the original question

Sort List 

Sort A linked list inO(NLogN) time using constant space complexity.

Second, analysis

The time complexity for quick sorting and merging sorting is O (Nlogn). If you use a merge sort, you do not need to re-apply the space to hold the sorted array in the case of a linked list, you can do the spatial complexity of the degree O (1). Here I use merge sort to sort the list.

Third, code (Java)

<pre name= "code" class= "java" >/** * Definition for singly-linked list. * Class  ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; *} * } */public Class Solution {public ListNode sortlist (ListNode head) {if (head==null) return Null;head=me Rgesort (head); return head;} Public ListNode mergesort (ListNode start) {if (start.next==null) return start; ListNode P1,p2,pre; 
P1=p2=pre=start;while (p1!=null) {    //divides the original linked list into equal-length two-part if (p1.next!=null) {p1=p1.next.next;pre=p2;p2=p2.next;// P2 is the midpoint}else break;} Pre.next=null;start=mergesort (start);p 2=mergesort (p2); Start=merge (START,P2); return start;} Public  listnode Merge (ListNode L1,listnode L2) {listnode start,temp,pre;pre=new listnode (0); if (l1.val<=l2.val Start = L1;elsestart = L2;temp=null;while ((l1!=null) && (l2!=null)) {if (l1.val<=l2.val) {pre.next=l1; temp= L1.next; L1.NEXT=L2; L1=temp;         Pre=pre.next; } else{pre.next=l2; temp=l2.next; l2.next=l1; l2=temp;         Pre=pre.next; }}    return start;}}



"Leetcode" Sort list Solution

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.