LeetCode: Sort List

LeetCode: Sort List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

/**
* Description
*
* @author hzhou
*/
public class SortList {
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;
}
fast = slow;
slow = slow.next;
fast.next = null;
fast = sortList(head);
slow = sortList(slow);
return merge(fast, slow);
}
private ListNode merge(ListNode a, ListNode b) {
ListNode result;
if (a == null) {
return b;
}
if (b == null) {
return a;
}
if (a.val >= b.val) {
result = b;
b = b.next;
} else {
result = a;
a = a.next;
}
ListNode cursor = result;
while (a != null && b != null) {
if (a.val >= b.val) {
cursor.next = b;
b = b.next;
} else {
cursor.next = a;
a = a.next;
}
cursor = cursor.next;
}
cursor.next = a == null ? b : a;
return result;
}
@Test
public void test() {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
sortList(head);
}
}