4231
42 31
4 2 3 1
--------------------------------------------------------------------
24 13
1234
public ListNode split(ListNode head){
if (head == null) return head;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode combine(ListNode one, ListNode two){
ListNode newHead = new ListNode(0); //return pointer
ListNode head = newHead; //travelling pointer
while (one != null && two != null){
if (one.value < two.value){
head.next = one;
head = one;
one = one.next;
} else {
head.next = two;
head = two;
two = two.next;
}
}
if (one != null){
while(one != null){
head.next = one;
head = one;
one = one.next;
}
}
if (two != null){
while (two != null){
head.next = two;
head = two;
two = two.next;
}
}
return newHead.next;
}
public ListNode mergeSort(ListNode head) {
if ( head == null || head.next == null) return head; //if len 1 or null
ListNode middle = split(head);
ListNode middleNext = middle.next;
middle.next = null;
ListNode left = mergeSort(head);
ListNode right = mergeSort(middleNext);
ListNode res = combine(left, right);
return res;
}