Skip to content

Instantly share code, notes, and snippets.

@ani03sha
Created September 16, 2020 13:46
Show Gist options
  • Save ani03sha/862f7f948a7b300798d0276eb97e59a7 to your computer and use it in GitHub Desktop.
Save ani03sha/862f7f948a7b300798d0276eb97e59a7 to your computer and use it in GitHub Desktop.
var mergeTwoLists = function(l1, l2) {
// If the first list is null then return the second list
// Because there is nothing to compare with the second list
if (!l1) {
return l2;
}
// If the second list is null then return the first list
// Because there is nothing to compare with the first list
if (!l2) {
return l1;
}
// This is the head of the new linked list which we will return
let head = null;
// We will use this "temp" variable to traverse the new list
let temp = head;
// Check for the head of the new list
// The new head will be chosen from the head of the list which has a smaller value
if(l1.val < l2.val) {
// Since there is only one node until now, both head and temp will be equal
temp = head = new ListNode(l1.val);
l1 = l1.next;
} else {
temp = head = new ListNode(l2.val);
l2 = l2.next;
}
// Loop until one of the list has elements.
// Even if elements in one of the list are finished, we will come out of the loop
while (l1 && l2) {
// Now, create a new node and store the data from list 1 or list 2
// depending on which list's node has the smaller value
if (l1.val < l2.val) {
// New node is created which will be the next of the current temp
// and it will store the data from the list 1's node
temp.next = new ListNode(l1.val);
// Since we have taken node from list 1, we will move to its next node
l1 = l1.next;
// Move temp to the current position so that we can add nodes further
temp = temp.next;
} else {
// New node is created which will be the next of the current temp
// and it will store the data from the list 2's node
temp.next = new ListNode(l2.val);
// Since we have taken node from list 2, we will move to its next node
l2 = l2.next;
// Move temp to the current position so that we can add nodes further
temp = temp.next;
}
}
// This loop will check if we have nodes left in the list 1
// And add all the remaining nodes in the new list
while (l1) {
temp.next = new ListNode(l1.val);
l1 = l1.next;
temp = temp.next;
}
// This loop will check if we have nodes left in the list 2
// And add all the remaining nodes in the new list
while (l2) {
temp.next = new ListNode(l2.val);
l2 = l2.next;
temp = temp.next;
}
// At the end, we will return the head of the new list
return head;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment