Merge Two Sorted Lists
Difficulty: Easy · Pattern: Linked List · LeetCode #21
Merge two sorted linked lists into one sorted list by splicing their nodes together (no new value nodes needed), and return its head.
Examples
text
1 → 4 → 6 and 2 → 3 → 7 → 1 → 2 → 3 → 4 → 6 → 7
(empty) and 0 → 0Hints
- Repeatedly take the smaller of the two current heads.
- A dummy head node avoids special-casing the first pick.
- When one list runs out, attach the rest of the other.
Approach
Create a dummy node and a tail pointer. While both lists are non-empty, attach the smaller head to tail.next and advance that list and tail. When one list is exhausted, link tail.next to the remaining list, since it's already sorted. Return dummy.next.
Complexity
Time: O(m + n). Space: O(1).
Python solution
def mergeTwoLists(list1, list2):
dummy = tail = ListNode()
while list1 and list2:
if list1.val <= list2.val:
tail.next, list1 = list1, list1.next
else:
tail.next, list2 = list2, list2.next
tail = tail.next
tail.next = list1 or list2
return dummy.nextJavaScript solution
function mergeTwoLists(list1, list2) {
const dummy = new ListNode();
let tail = dummy;
while (list1 && list2) {
if (list1.val <= list2.val) { tail.next = list1; list1 = list1.next; }
else { tail.next = list2; list2 = list2.next; }
tail = tail.next;
}
tail.next = list1 || list2;
return dummy.next;
}