21. Merge Two Sorted Lists
Problem
https://leetcode.com/problems/merge-two-sorted-lists/
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Solution
Loop and compare in parallel.
Beware of the history bug. Use if(object !== null) instead of if(object)because the latter always returns true.
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
if (!(l1 instanceof ListNode) || !(l2 instanceof ListNode)) {
if (l1 instanceof ListNode) { return l1 }
if (l2 instanceof ListNode) { return l2 }
return null
}
let head
let p1 = l1
let p2 = l2
if (p1.val <= p2.val) {
head = p1
p1 = p1.next
} else {
head = p2
p2 = p2.next
}
let p = head
while (p1 !== null && p2 !== null) {
if (p1.val <= p2.val) {
p.next = p1
p1 = p1.next
} else {
p.next = p2
p2 = p2.next
}
p = p.next
}
p.next = p1 === null ? p2 : p1
return head
};