Algo-Sim › Linked Lists
Merge Two Sorted Lists
Easy · Linked Lists · step through it in Java, Python and C++ on your own input
Splice two sorted lists into one sorted list by relinking nodes behind a dummy head.
Problem
Given the heads of two linked lists, each sorted in non-decreasing order, splice their nodes together into one sorted list and return its head.
Constraints
- 0 ≤ nodes in each list ≤ 50
- -100 ≤ Node.val ≤ 100
- Both lists are sorted in non-decreasing order
Edge cases to test
- One or both lists empty
- Equal values in both lists
- One list entirely smaller than the other
Follow-up questions
- Why a dummy head?
- It removes the special case for the first node: always append to
tail.next. O(m + n), O(1) extra. - How do you merge k lists?
- A min-heap of list heads (O(N log k)) or pairwise merging in rounds (also O(N log k)).
Solution
Java
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0), tail = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
tail.next = list1;
list1 = list1.next;
} else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}
tail.next = (list1 != null) ? list1 : list2;
return dummy.next;
}Python
def merge_two_lists(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 if list1 else list2
return dummy.nextC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
ListNode *dummy = new ListNode(0), *tail = dummy;
while (list1 != nullptr && list2 != nullptr) {
if (list1->val <= list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
tail->next = (list1 != nullptr) ? list1 : list2;
return dummy->next;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)