Sort a linked list in O(n log n) time using constant space complexity.
The tricky point of this problem is that these number stored in a linked list instead of an array. We could use merge sort for this problem. We need to seperate the list into two part and cut the link between them. Then recursively sort them and merge them together.
The merge algorithm is also a bit complicated since it's a linked list. In this implementation, we need to maintain two list. In the comparison of two nodes in list1 and list2. If 1 < 2, we continue to the next node of list1, else we would swap list2 up to become the next node of list and swap list1 down.
public class Solution {
public static ListNode sortList(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode start = head;
while(head.next != null)
{
head = head.next;
}
ListNode end = head;
ListNode a = mergeSort(start, end);
return a;
}
public static ListNode mergeSort(ListNode start, ListNode end)
{
if(start == end) return start;
if(start.next == end)
{
if(start.val > end.val)
{
int temp = start.val;
start.val = end.val;
end.val = temp;
return start;
}
else return start;
}
ListNode node1 = start;
ListNode node2 = start;
while(node2 != end && node2.next != end)
{
node1 = node1.next;
node2 = node2.next.next;
}
ListNode middleNext = node1.next;
node1.next = null;
node1 = mergeSort(start, node1);
node2 = mergeSort(middleNext, end);
ListNode b = merge(node1, node2);
return b;
}
public static ListNode merge(ListNode list1, ListNode list2)
{
if (list1 == null) return list2;
if (list2 == null) return list1;
ListNode head;
if (list1.val < list2.val)
{
head = list1;
} else {
head = list2;
list2 = list1;
list1 = head;
}
while(list1.next != null && list2 != null) {
if (list1.next.val <= list2.val) {
list1 = list1.next;
} else {
ListNode tmp = list1.next;
list1.next = list2;
list2 = tmp;
list1 = list1.next;
}
}
if (list1.next == null) list1.next = list2;
return head;
}
}