-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path148. Sort List.java
54 lines (45 loc) · 1.27 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
class Solution {
public ListNode sortList(ListNode head) {
// applying the mserg sort algorithm for this
if(head==null || head.next==null){
return head;
}
ListNode mid=find_mid(head);
ListNode left=sortList(head);
ListNode right=sortList(mid);
return merge_sort(left,right);
}
private ListNode find_mid(ListNode head){
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null && fast.next.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode mid=slow.next;
slow.next=null;
return mid;
}
public ListNode merge_sort(ListNode left,ListNode right){
ListNode dummy=new ListNode(-1);
ListNode current=dummy;
while(left!=null && right!=null){
if(left.val<=right.val){
current.next=left;
left=left.next;
}
else{
current.next=right;
right=right.next;
}
current=current.next;
}
if(left!=null){
current.next=left;
}
if(right!=null){
current.next=right;
}
return dummy.next;
}
}