-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path148.Sort-List.java
62 lines (53 loc) · 1.31 KB
/
148.Sort-List.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
// https://leetcode.com/problems/sort-list/
//
// algorithms
// Medium (34.81%)
// Total Accepted: 179,359
// Total Submissions: 515,226
/**
* 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 || head.next == null) {
return head;
}
ListNode l = head, r = head.next, pre = null;
while (r != null) {
pre = l;
l = l.next;
r = r.next;
if (r != null) {
r = r.next;
}
}
pre.next = null;
r = this.sortList(l);
l = this.sortList(head);
ListNode res = new ListNode(-1);
ListNode tmp = res;
while (l != null && r != null) {
if (l.val <= r.val) {
res.next = l;
l = l.next;
} else {
res.next = r;
r = r.next;
}
res = res.next;
res.next = null;
}
if (l != null) {
res.next = l;
}
if (r != null) {
res.next = r;
}
return tmp.next;
}
}