-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path148.sort-list.java
55 lines (51 loc) · 1.41 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode middle = getMid(head);
ListNode next = middle.next;
middle.next = null;
ListNode lft = sortList(head);
ListNode rgt = sortList(next);
return msort(lft, rgt);
}
public ListNode msort(ListNode l, ListNode r){
if(l == null)
return r;
if(r == null)
return l;
ListNode res = null;
// while(l != null && r != null){
if(l.val <= r.val){
res = l;
res.next = msort(l.next, r);
}
else{
res = r;
res.next = msort(l, r.next);
}
// }
return res;
}
public ListNode getMid(ListNode root){
if(root == null)
return root;
ListNode slow = root;
ListNode fast = root;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}