Merge Two Sorted Lists
Linked ListTwo Pointers
Problem Statement
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4]
List 1
List 2
Output: [1,1,2,3,4,4]
Constraints
- The number of nodes in both lists is in the range [0, 50].
- -100 ≤ Node.val ≤ 100
- Both
list1
andlist2
are sorted in non-decreasing order.
Iterative Solution Walkthrough
The iterative approach merges two sorted lists by repeatedly comparing the heads of the lists and appending the smaller node to the result.
List 1
1
p1
2
4
List 2
1
p2
3
4
Merged List
empty
Click 'Next' to start the merge process.
Algorithm Steps
- Create a dummy node to start the merged list.
- Compare the nodes at the current pointers of both lists.
- Append the smaller node to the merged list and advance its pointer.
- Repeat until one list is empty.
- Append the remaining portion of the non-empty list.
Iterative Solution