Skip to content

Instantly share code, notes, and snippets.

@cxtadment
Created September 2, 2015 05:06
Show Gist options
  • Select an option

  • Save cxtadment/ea579ec57d4f54094830 to your computer and use it in GitHub Desktop.

Select an option

Save cxtadment/ea579ec57d4f54094830 to your computer and use it in GitHub Desktop.
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list,
using constant space complexity.
*/
public ListNode sortList(ListNode head) {
// write your code here
if (head == null || head.next == null) {
return head;
}
ListNode midNode = getMid(head);
ListNode right = sortList(midNode.next);
midNode.next = null;
ListNode left = sortList(head);
return merge(left, right);
}
private ListNode getMid(ListNode head) {
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
private ListNode merge(ListNode left, ListNode right) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (left != null && right != null) {
if (left.val <= right.val) {
curr.next = left;
curr = curr.next;
left = left.next;
} else {
curr.next = right;
curr = curr.next;
right = right.next;
}
}
if (left != null) {
curr.next = left;
} else {
curr.next = right;
}
return dummy.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment