forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortList.java
More file actions
88 lines (67 loc) · 1.8 KB
/
SortList.java
File metadata and controls
88 lines (67 loc) · 1.8 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package LinkedLists;
/**
* Author - archit.s
* Date - 21/10/18
* Time - 4:19 PM
*/
public class SortList {
ListNode getMiddle(ListNode h){
if(h == null){
return null;
}
ListNode slow = h;
ListNode fast = h.next;
while(fast!=null){
fast = fast.next;
if(fast!=null){
slow = slow.next;
fast = fast.next;
}
}
return slow;
}
ListNode sortedMerge(ListNode left, ListNode right){
ListNode result = new ListNode(0);
ListNode last = result;
while(left!=null && right!=null){
if(left.val<=right.val){
last.next = left;
left = left.next;
}
else{
last.next = right;
right = right.next;
}
last= last.next;
}
if(left == null){
last.next = right;
}
if(right == null){
last.next = left;
}
return result.next;
}
ListNode mergeSort(ListNode root){
if(root == null || root.next == null){
return root;
}
ListNode middle = getMiddle(root);
ListNode nextToMiddle = middle.next;
middle.next = null;
ListNode left = mergeSort(root);
ListNode right = mergeSort(nextToMiddle);
ListNode result = sortedMerge(left,right);
return result;
}
public ListNode sortList(ListNode A) {
return mergeSort(A);
}
public static void main(String[] args) {
ListNode r = new ListNode(1);
r.next = new ListNode(3);
r.next.next = new ListNode(3);
r.next.next.next = new ListNode(0);
System.out.println(new SortList().sortList(r));
}
}