/Sort List.java Secret
Created
January 16, 2014 02:56
Sort a linked list in O(n log n) time using constant space complexity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sort a linked list in O(n log n) time using constant space complexity. | |
/** | |
* 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||head.next==null){ | |
return head; | |
} | |
ListNode fast=head; | |
ListNode slow=head; | |
while(fast.next!=null && fast.next.next!=null){ | |
fast=fast.next.next; | |
slow=slow.next; | |
} | |
ListNode right=slow.next; | |
slow.next=null; | |
ListNode left=head; | |
left =sortList(left); | |
right=sortList(right); | |
return merge(left, right); | |
} | |
private ListNode merge(ListNode left, ListNode right){ | |
if (left==null){ | |
return right; | |
} | |
if (right==null){ | |
return left; | |
} | |
ListNode preHead=new ListNode(-1); | |
ListNode end=preHead; | |
while (left!=null && right!=null){ | |
if (left.val<right.val){ | |
end.next=left; | |
left=left.next; | |
} | |
else{ | |
end.next=right; | |
right=right.next; | |
} | |
end=end.next; | |
} | |
if (left!=null){ | |
end.next=left; | |
} | |
if (right!=null){ | |
end.next=right; | |
} | |
return preHead.next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment