Created
December 25, 2022 05:30
-
-
Save thmain/ad8766ebcced30054569bb112807abb0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mergeTwoSortedLists (l1, l2) { | |
let mergedLinkedListHead = { val : -1, next : null }; // create dummy node to get started | |
let runner = mergedLinkedListHead; | |
while(l1 && l2) { | |
if(l1.val > l2.val) { | |
runner.next = l2; | |
l2 = l2.next; | |
} else { | |
runner.next = l1; | |
l1 = l1.next; | |
} | |
runner = runner.next; | |
} | |
// l1 = 1->2->3, l2 = 10->20->30 | |
// In that case l1, will point to null and while loop will break | |
// Simply point runner to l2. We do not have to add individual nodes | |
runner.next = l1 || l2; | |
return mergedLinkedListHead.next; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment