-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
36 lines (34 loc) · 984 Bytes
/
Copy pathSolution.java
File metadata and controls
36 lines (34 loc) · 984 Bytes
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
public class Solution
{
public ListNode sortList(ListNode head)
{
if (head == null || head.next == null)
{
return head;
}
ListNode mid = head, fast = head, prev = null;
while (fast != null && fast.next != null)
{
prev = mid;
mid = mid.next;
fast = fast.next.next;
}
prev.next = null;
return merge(sortList(head), sortList(mid));
}
private ListNode merge(ListNode a, ListNode b)
{
ListNode dummy = new ListNode(-1);
ListNode merge = dummy;
while (a != null || b != null)
{
int a_val = a != null ? a.val : Integer.MAX_VALUE;
int b_val = b != null ? b.val : Integer.MAX_VALUE;
merge.next = a_val > b_val ? b : a;
a = a_val > b_val ? a : a.next;
b = a_val > b_val ? b.next : b;
merge = merge.next;
}
return dummy.next;
}
}