Skip to content

Instantly share code, notes, and snippets.

@fxxz
Created October 18, 2015 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fxxz/058689f7ecfb4633755b to your computer and use it in GitHub Desktop.
Save fxxz/058689f7ecfb4633755b to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode head1 = head;
ListNode head2 = slow.next;
slow.next = null;
head1 = sortList(head1);
head2 = sortList(head2);
return merge(head1, head2);
}
private ListNode merge(ListNode head1, ListNode head2) {
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
ListNode dummyNode = new ListNode(0);
ListNode curr = dummyNode;
while (head1 != null && head2 != null) {
if (head1.val <= head2.val) {
curr.next = head1;
head1 = head1.next;
} else {
curr.next = head2;
head2 = head2.next;
}
curr = curr.next;
}
curr.next = head1 == null ? head2 : head1;
return dummyNode.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment