Yup… oddly like merging into traffic. 😆 😂 😝
The Prompt:Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Illustration: Merging two sorted linked lists
  1. Our input is two sorted linked lists; their values are sorted but not sequenced like 1,2,3,4,5…
  2. Conditional Logic: Lower values always are inserted first, so the position doesn’t matter
  3. How will I settle ties? Let’s make the default list be “l1”.
  4. We will need to update our references after each node gets inserted into our new list.
  5. We will use a loop to move through the linked lists.
  6. Sometimes a linked list can insert its nodes more than once since it could have the lowest value.
class List {
constructor(val = null, next = null) {
this.val = val <= number value of current node
this.next = next <= rest of values AFTER current node !
}
}
let mergeTwoLists = function(l1, l2) {let result = new List(-1)
let head = result
}
while(l1 !== null && l2 !== null) {

... Both lists shouldn't be null ...

};
Note: use '<=' , it deals with any ties !!!if(l1.val <= l2.val) {  ...  } 

result = result.next <= so we don't overwrite our added node !!!
if(l1.val <= l2.val) {.   <= what's the lower value? Who wins ???            result.next = l1.next   <= if winner, add whole list 
l1 = l1.next <= update list without current value
} else {
result.next = l2.next <= if winner, same deal
l2 = l2.next <= update the same way
...
  • Null is when the shorter or first list empties.
  • We need to return the newly merged list.
if(l1 !== null) {          <= If first list IS NOT null
result.next = l1 <= add rest of list to result

} else {
result.next = l2 <= add rest of list to result
}

return head.next <= We don't want the first value, just everything after it
};
const mergeTwoLists = function(l1, l2) {
let result = new List(-1)
let head = result

while(l1 !== null && l2 !== null) {

if(l1.val <= l2.val) {
result.next = l1
l1 = l1.next
} else {
result.next = l2
l2 = l2.next
}
result = result.next
};

if(l1 !== null) {
result.next = l1

} else {
result.next = l2
}

return head.next

};
class List {
constructor(val = null, next = null) {
this.val = val
this.next = next
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store