Overview
Given the heads of two sorted linked lists, merge them into a single sorted linked list by splicing together the nodes from both lists. Return the head of the merged list.
Constraints
- Both lists are sorted in ascending order.
- The total number of nodes is in range
[0, 100]. - Node values are in range
[-100, 100].
Examples
// list1: 1->2->4 // list2: 1->3->4 mergeTwoLists(list1, list2); // => 1->1->2->3->4->4
// Both empty
mergeTwoLists(null, null);
// => null
// One empty
mergeTwoLists(null, { val: 0, next: null });
// => 0Solution
Reveal solution
function mergeTwoLists(list1, list2) {
const dummy = { val: 0, next: null };
let curr = dummy;
while (list1 && list2) {
if (list1.val <= list2.val) {
curr.next = list1;
list1 = list1.next;
} else {
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
}
curr.next = list1 || list2;
return dummy.next;
}Resources
linked-lists-combine-two-sorted.js
Linked Lists Combine Two Sorted
easycodingAlgorithmsLinked Lists
Overview
Given the heads of two sorted linked lists, merge them into a single sorted linked list by splicing together the nodes from both lists. Return the head of the merged list.
Constraints
- Both lists are sorted in ascending order.
- The total number of nodes is in range
[0, 100]. - Node values are in range
[-100, 100].
Examples
// list1: 1->2->4 // list2: 1->3->4 mergeTwoLists(list1, list2); // => 1->1->2->3->4->4
// Both empty
mergeTwoLists(null, null);
// => null
// One empty
mergeTwoLists(null, { val: 0, next: null });
// => 0Solution
Reveal solution
function mergeTwoLists(list1, list2) {
const dummy = { val: 0, next: null };
let curr = dummy;
while (list1 && list2) {
if (list1.val <= list2.val) {
curr.next = list1;
list1 = list1.next;
} else {
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
}
curr.next = list1 || list2;
return dummy.next;
}Resources
NameTopicDifficulty
103 of 103 problems