class Node{
constructor(data){
this
.data = data;
this
.next =
null
;
}
}
class pair{
constructor(first, second){
this
.first = first;
this
.second = second;
}
}
function
push(head_ref, new_data){
let new_node =
new
Node(new_data);
new_node.next = head_ref;
head_ref = new_node;
return
head_ref;
}
function
FrontBackSplit(head){
if
(head ==
null
)
return
head;
let slow = head;
let fast = head;
while
(fast.next !=
null
&& fast.next.next !=
null
){
slow = slow.next;
fast = fast.next.next;
}
return
slow;
}
function
SortedMerge(a, b){
let result =
null
;
if
(a ==
null
)
return
b;
else
if
(b ==
null
)
return
a;
if
(a.data <= b.data){
result = a;
result.next = SortedMerge(a.next, b);
}
else
{
result = b;
result.next = SortedMerge(a, b.next);
}
return
result;
}
function
mergeSort(head){
if
(head ==
null
|| head.next ==
null
)
return
head;
let middle = FrontBackSplit(head);
let nextofmiddle = middle.next;
middle.next =
null
;
let left = mergeSort(head);
let right = mergeSort(nextofmiddle);
return
SortedMerge(left, right);
}
function
getUnion(head1, head2){
let result =
null
;
let t1 = head1;
let t2 = head2;
while
(t1 !=
null
&& t2 !=
null
){
if
(t1.data < t2.data){
result = push(result, t1.data);
t1 = t1.next;
}
else
if
(t1.data > t2.data){
result = push(result, t2.data);
t2 = t2.next;
}
else
{
result = push(result, t2.data);
t1 = t1.next;
t2 = t2.next;
}
}
while
(t1 !=
null
) {
result = push(result, t1.data);
t1 = t1.next;
}
while
(t2 !=
null
) {
result = push(result, t2.data);
t2 = t2.next;
}
return
result;
}
function
getIntersection(head1, head2){
let result =
null
;
let t1 = head1, t2 = head2;
while
(t1 !=
null
&& t2 !=
null
) {
if
(t1.data < t2.data)
t1 = t1.next;
else
if
(t1.data > t2.data)
t2 = t2.next;
else
{
result = push(result, t2.data);
t1 = t1.next;
t2 = t2.next;
}
}
return
result;
}
function
printList(node){
while
(node !=
null
) {
console.log(node.data +
" "
);
node = node.next;
}
}
let head1 =
null
;
let head2 =
null
;
let intersection_list =
null
;
let union_list =
null
;
head1 = push(head1, 20);
head1 = push(head1, 4);
head1 = push(head1, 15);
head1 = push(head1, 10);
head1 = push(head1, 11);
head2 = push(head2, 10);
head2 = push(head2, 2);
head2 = push(head2, 4);
head2 = push(head2, 8);
head1 = mergeSort(head1);
head2 = mergeSort(head2);
intersection_list = getIntersection(head1, head2);
union_list = getUnion(head1, head2);
console.log(
"First list is "
);
printList(head1);
console.log(
"\nSecond list is "
);
printList(head2);
console.log(
"\nIntersection list is "
);
printList(intersection_list);
console.log(
"\nUnion list is "
);
printList(union_list);