-
Notifications
You must be signed in to change notification settings - Fork 8
/
Solution.java
73 lines (65 loc) · 1.66 KB
/
Solution.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
65
66
67
68
69
70
71
72
73
/**
* Created by Inno Fang on 2018/3/15.
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
/**
* 15 / 15 test cases passed.
* Status: Accepted
* Runtime: 7 ms
*/
class Solution {
public ListNode sortList(ListNode head) {
return mergeSort(head);
}
private ListNode mergeSort(ListNode head) {
if (head == null || head.next == null) return head;
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next;
if (fast.next != null) {
fast = fast.next;
}
}
ListNode ptr = slow.next;
slow.next = null;
ListNode node1 = mergeSort(head);
ListNode node2 = mergeSort(ptr);
return merge(node1, node2);
}
private ListNode merge(ListNode node1, ListNode node2) {
ListNode head = new ListNode(-1);
ListNode cur = head;
ListNode ptr1 = node1;
ListNode ptr2 = node2;
while (null != ptr1 && null != ptr2) {
if (ptr1.val > ptr2.val) {
cur.next = ptr2;
ptr2 = ptr2.next;
cur = cur.next;
} else {
cur.next = ptr1;
ptr1 = ptr1.next;
cur = cur.next;
}
}
while (null != ptr1) {
cur.next = ptr1;
cur = cur.next;
ptr1 = ptr1.next;
}
while (null != ptr2) {
cur.next = ptr2;
cur = cur.next;
ptr2 = ptr2.next;
}
return head.next;
}
}