kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 148. Sort List

148. Sort List

Difficulty: Medium

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

1
2
Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

1
2
Input: -1->5->3->4->0
Output: -1->0->3->4->5

Solution

Language: Java

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
61
62
63
64
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null) {
return head;
}
return sort(head);
}

private ListNode sort(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
fast = slow.next;
slow.next = null;
head = sort(head);
fast = sort(fast);
return merge(head, fast);
}

private ListNode merge(ListNode head1, ListNode head2) {
ListNode head;
if (head1.val < head2.val) {
head = head1;
head1 = head1.next;
} else {
head = head2;
head2 = head2.next;
}
ListNode cur = head;
while (head1 != null || head2 != null) {
if (head1 == null) {
cur.next = head2;
head2 = head2.next;
} else if (head2 == null) {
cur.next = head1;
head1 = head1.next;
} else if (head1.val < head2.val) {
cur.next = head1;
head1 = head1.next;
} else {
cur.next = head2;
head2 = head2.next;
}
cur = cur.next;
cur.next = null;
}
return head;
}

}