-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path148. Sort List
More file actions
46 lines (44 loc) · 1.21 KB
/
148. Sort List
File metadata and controls
46 lines (44 loc) · 1.21 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
//O(nlogn) time and O(logn) space
class Solution {
public ListNode sortList(ListNode head) {
//Sanity check
if(head==null || head.next==null) return head;
ListNode slow = head, fast = head, prev = null;
while(fast!=null && fast.next!=null){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
return merge(l1,l2);
}
//O(m+n) time and O(1) space
public ListNode merge(ListNode l1, ListNode l2){
ListNode dummy = new ListNode(0);
ListNode iter = dummy;
while(l1!=null && l2!=null){
if(l1.val<=l2.val){
iter.next = l1;
l1 = l1.next;
}
else{
iter.next = l2;
l2 = l2.next;
}
iter = iter.next;
}
while(l1!=null){
iter.next = l1;
l1 = l1.next;
iter = iter.next;
}
while(l2!=null){
iter.next = l2;
l2 = l2.next;
iter = iter.next;
}
return dummy.next;
}
}