Skip to content

Commit 67358aa

Browse files
committed
Added doubly linked list mergesort example
1 parent bda9407 commit 67358aa

File tree

1 file changed

+94
-9
lines changed

1 file changed

+94
-9
lines changed

LinkedListQuestion.java

+94-9
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,104 @@ public static void main(String[] args) throws Exception {
3333
void solve() throws Exception {
3434
// reverseLinkedList();
3535
//detect_and_remove_loop();
36+
double_merge_sort();
37+
}
38+
39+
void double_merge_sort(){
40+
dpush(15);
41+
dpush(10);
42+
dpush(5);
43+
dpush(20);
44+
dpush(2);
45+
dpush(3);
3646

37-
push(15);
38-
push(10);
39-
push(5);
40-
push(20);
41-
push(2);
42-
push(3);
47+
dprintList(dhead);
48+
dhead = mergeSortList(dhead);
49+
dprintList(dhead);
50+
}
51+
52+
DoubleListNode dhead;
53+
54+
class DoubleListNode {
55+
int val;
56+
DoubleListNode next;
57+
DoubleListNode prev;
58+
59+
DoubleListNode(int x) {
60+
val = x;
61+
}
62+
}
63+
64+
DoubleListNode mergeSortList(DoubleListNode head) {
65+
66+
if (head == null || head.next == null)
67+
return head;
68+
69+
DoubleListNode second = split(head);
70+
71+
head = mergeSortList(head);
72+
second = mergeSortList(second);
73+
74+
return merge(head,second);
75+
}
76+
77+
DoubleListNode merge(DoubleListNode l, DoubleListNode r) {
78+
if(l == null)
79+
return r;
80+
if(r == null)
81+
return l;
4382

44-
printList(head);
45-
head = mergeSortList(head);
46-
printList(head);
83+
if(l.val < r.val){
84+
l.next = merge(l.next, r);
85+
l.next.prev = l;
86+
l.prev = null;
87+
return l;
88+
}else{
89+
r.next = merge(l, r.next);
90+
r.next.prev = r;
91+
r.prev = null;
92+
return r;
93+
}
94+
}
95+
96+
DoubleListNode split(DoubleListNode head){
97+
DoubleListNode fast = head, slow = head;
98+
while(fast.next != null && fast.next.next != null){
99+
fast = fast.next.next;
100+
slow = slow.next;
101+
}
102+
DoubleListNode temp = slow.next;
103+
slow.next = null;
104+
return temp;
47105
}
48106

107+
void dpush(int data){
108+
DoubleListNode new_node = new DoubleListNode(data);
109+
if(dhead!=null)
110+
dhead.prev = new_node;
111+
new_node.next = dhead;
112+
dhead = new_node;
113+
}
114+
115+
void dprintList(DoubleListNode x) {
116+
if(x != null){
117+
DoubleListNode temp = null;
118+
pout.println("forward:");
119+
while (x != null) {
120+
pout.print(x.val + " ");
121+
temp = x;
122+
x = x.next;
123+
}
124+
pout.println();
125+
pout.println("backward:");
126+
while(temp != null){
127+
pout.print(temp.val + " ");
128+
temp = temp.prev;
129+
}
130+
pout.println();
131+
}
132+
}
133+
49134
ListNode head;
50135

51136
class ListNode {

0 commit comments

Comments
 (0)