-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListSort.java
72 lines (67 loc) · 1.61 KB
/
LinkedListSort.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class LinkedListSort {
static class LinkedList {
int data;
LinkedList next;
LinkedList(){}
LinkedList(int d){
this.data = d;
this.next = null;
}
};
static LinkedList head;
private static LinkedList sort(LinkedList head){
if(head == null || head.next == null){
return head;
}
LinkedList middle = getMiddle(head);
LinkedList nextOfMiddle = middle.next;
middle.next = null;
LinkedList left = sort(head);
LinkedList right = sort(nextOfMiddle);
return merge(left, right);
}
private static LinkedList merge(LinkedList left, LinkedList right){
if(left == null){
return right;
}
if(right == null){
return left;
}
LinkedList result = null;
if(left.data <= right.data){
result = left;
result.next = merge(left.next, right);
} else {
result = right;
result.next = merge(left, right.next);
}
return result;
}
private static LinkedList getMiddle(LinkedList head){
LinkedList slow = head;
LinkedList fast = head;
boolean flag = false;
while(fast.next != null){
if(!flag){
fast = fast.next;
flag = true;
} else {
slow = slow.next;
fast = fast.next;
}
}
return slow;
}
public static void main(String args[]){
head = new LinkedList(2);
head.next = new LinkedList(1);
head.next.next = new LinkedList(4);
head.next.next.next = new LinkedList(3);
head = sort(head);
LinkedList ptr = head;
while(ptr != null){
System.out.print(ptr.data+" ");
ptr = ptr.next;
}
}
}