- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathSortList148.java
More file actions
Latest commit
55 lines (48 loc) · 1.27 KB
/
Copy pathSortList148.java
File metadata and controls
55 lines (48 loc) · 1.27 KB
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
/**
* Sort a linked list in O(n log n) time using constant space complexity.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
publicclassSortList148 {
publicListNodesortList(ListNodehead) {
if (head == null) returnnull;
if (head.next == null) returnhead;
ListNodes = head;
ListNodef = head;
ListNodepre = s;
while (s != null && f != null && f.next != null) {
pre = s;
s = s.next;
f = f.next.next;
}
pre.next = null;
ListNodeleft = sortList(head);
ListNoderight = sortList(s);
returnmerge(left, right);
}
privateListNodemerge(ListNodeleft, ListNoderight) {
ListNoderes = newListNode(-1);
ListNodep = res;
ListNodel = left;
ListNoder = right;
while (l != null && r != null) {
if (l.val <= r.val) {
p.next = l;
l = l.next;
} else {
p.next = r;
r = r.next;
}
p = p.next;
}
if (l != null) p.next = l;
if (r != null) p.next = r;
returnres.next;
}
}