-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_148_SortList.java
More file actions
100 lines (76 loc) · 2.17 KB
/
_148_SortList.java
File metadata and controls
100 lines (76 loc) · 2.17 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
89
90
91
92
93
94
95
96
97
98
99
100
class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
this.next = null;
}
}
public class _148_SortList {
public static ListNode sortList(ListNode head){
//base case
if (head == null || head.next == null) {
return head;
}
//step 1 find middle
ListNode mid = getMid(head);
ListNode right = mid.next;
mid.next = null;
//step 2 Sort Both halves
ListNode leftSort = sortList(head);
ListNode rightSort = sortList(right);
// 3 merge
return merge(leftSort,rightSort);
}
private static ListNode getMid(ListNode head){
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// merge Two Sort List
private static ListNode merge(ListNode l1, ListNode l2){
ListNode dummy = new ListNode(-1);
ListNode temp = dummy;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
temp.next = l1;
l1 = l1.next;
}else{
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if (l1 != null) {
temp.next = l1;
}else{
temp.next = l2;
}
return dummy.next;
}
// -------- PRINT LIST --------
private static void printList(ListNode head) {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + "->");
temp = temp.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
// Create list: 4->2->1->3
ListNode head = new ListNode(4);
head.next = new ListNode(2);
head.next.next = new ListNode(1);
head.next.next.next = new ListNode(3);
System.out.println("Before Sorting:");
printList(head);
head = sortList(head);
System.out.println("After Sorting:");
printList(head);
}
}