Skip to content

Instantly share code, notes, and snippets.

@nodeEnthu
Created May 1, 2020 18:14
Show Gist options
  • Save nodeEnthu/9aa1ae3c479faa6df3e4d5dfacd25741 to your computer and use it in GitHub Desktop.
Save nodeEnthu/9aa1ae3c479faa6df3e4d5dfacd25741 to your computer and use it in GitHub Desktop.
description to merging sorted linked lists
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