-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path148. Sort List.java
More file actions
54 lines (47 loc) · 1.25 KB
/
148. Sort List.java
File metadata and controls
54 lines (47 loc) · 1.25 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution{
ListNode merge(ListNode l1, ListNode l2){
ListNode dummyNode = new ListNode(0);
ListNode p = dummyNode;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
p.next = l1;
l1 = l1.next;
}else{
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if(l1 != null) p.next = l1;
if(l2 != null) p.next = l2;
return dummyNode.next;
}
public ListNode sortList(ListNode head){
if(head == null || head.next == null){
return head;
}
// Cut the list to two halves
ListNode prev = null;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
// Sort two halves
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
// Merge two halves
return merge(l1, l2);
}
}