function mergeLists(head1, head2) {
// handle empty list
if(!head1 || !head2){
return head1 || head2;
}
let sortedHead;
let leftNode =head1;
let rightNode = head2;
// set newHead
if(head1.data <= head2.data){
sortedHead = head1;
leftNode = leftNode.next;
} else{
sortedHead = head2;
rightNode = rightNode.next;
}
// merging
let sortedCurrentNode = sortedHead;
while(leftNode && rightNode){
if(leftNode.data <= rightNode.data){
sortedCurrentNode.next = leftNode;
leftNode = leftNode.next;
}
else{
sortedCurrentNode.next = rightNode;
rightNode = rightNode.next;
}
sortedCurrentNode=sortedCurrentNode.next;
}
// apending the remainders
while(leftNode){
sortedCurrentNode.next = leftNode;
leftNode=leftNode.next;
sortedCurrentNode=sortedCurrentNode.next;
}
while(rightNode){
sortedCurrentNode.next = rightNode;
rightNode=rightNode.next;
sortedCurrentNode=sortedCurrentNode.next;
}
return sortedHead;
}