<script>
var
head ;
class Node {
constructor(d) {
this
.data = d;
this
.next =
this
.prev =
null
;
}
}
function
print( node) {
temp = node;
document.write(
"Forward Traversal using next pointer<br/>"
);
while
(node !=
null
) {
document.write(node.data +
" "
);
temp = node;
node = node.next;
}
document.write(
"<br/>Backward Traversal using prev pointer<br/>"
);
while
(temp !=
null
) {
document.write(temp.data +
" "
);
temp = temp.prev;
}
}
function
split( head) {
fast = head, slow = head;
while
(fast.next !=
null
&& fast.next.next !=
null
) {
fast = fast.next.next;
slow = slow.next;
}
temp = slow.next;
slow.next =
null
;
return
temp;
}
function
mergeSort( node) {
if
(node ==
null
|| node.next ==
null
) {
return
node;
}
var
second = split(node);
node = mergeSort(node);
second = mergeSort(second);
return
merge(node, second);
}
function
merge( first, second) {
if
(first ==
null
) {
return
second;
}
if
(second ==
null
) {
return
first;
}
if
(first.data < second.data) {
first.next = merge(first.next, second);
first.next.prev = first;
first.prev =
null
;
return
first;
}
else
{
second.next = merge(first, second.next);
second.next.prev = second;
second.prev =
null
;
return
second;
}
}
head =
new
Node(10);
head.next =
new
Node(30);
head.next.next =
new
Node(3);
head.next.next.next =
new
Node(4);
head.next.next.next.next =
new
Node(20);
head.next.next.next.next.next =
new
Node(5);
node =
null
;
node = mergeSort(head);
document.write(
"Linked list after sorting :<br/>"
);
print(node);
</script>