Created
May 1, 2020 18:14
-
-
Save nodeEnthu/9aa1ae3c479faa6df3e4d5dfacd25741 to your computer and use it in GitHub Desktop.
description to merging sorted linked lists
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
var mergeTwoLists = function(l1, l2) { | |
const newNode = new ListNode(-1); | |
function mergeTwoListsRec(newL1Head, newL2Head, prevHead) { | |
if(!newL1Head || !newL2Head) { | |
prevHead.next = (newL1Head || newL2Head); | |
return; | |
} | |
const newHead = (newL1Head.val <= newL2Head.val) ? newL1Head : newL2Head; | |
prevHead.next = newHead; | |
if(newHead === newL1Head) newL1Head = newL1Head.next; | |
if(newHead === newL2Head) newL2Head = newL2Head.next; | |
mergeTwoListsRec(newL1Head, newL2Head, newHead); | |
} | |
mergeTwoListsRec(l1, l2, newNode); | |
return newNode.next; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment