merge two linked lists
by Steven Senkus
JavaScript
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
var mergeTwoLists = function(l1, l2) {
if (!l1 || !l2) return l1 || l2;
const r = new ListNode();
let l = r;
while (l1 && l2) {
if (l1.val < l2.val) {
l.val = l1.val;
l1 = l1.next;
} else if (l1.val > l2.val) {
l.val = l2.val;
l2 = l2.next;
} else {
l.val = l1.val;
l.next = new ListNode(l2.val);
l = l.next;
l1 = l1.next;
l2 = l2.next;
}
if (l1 && l2) {
l.next = new ListNode();
l = l.next;
}
}
if (l1) l.next = l1;
if (l2) l.next = l2;
return r;
}
const l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(4);
const l2 = new ListNode(1);
l2.next = new ListNode(3);
l2.next.next = new ListNode(4);
console.log(mergeTwoLists(l1, l2));