1. Problem Statement (Simple Explanation):
You are given the heads of two sorted singly linked lists: list1 and list2.
You must merge them into a single sorted linked list by reusing and splicing together the existing nodes (no need to create new nodes for values), and return the head of the merged list.
Both lists are sorted in non-decreasing order.
Either list may be empty.
2. Examples:
Example 1:
Input:
list1 = [1,2,4]
list2 = [1,3,4]
Merged list:
Compare 1 and 1 → pick either, say from list1 → [1]
Next compare 2 and 1 → pick 1 from list2 → [1,1]
Compare 2 and 3 → pick 2 → [1,1,2]
Compare 4 and 3 → pick 3 → [1,1,2,3]
Compare 4 and 4 → pick either 4 → then append remaining 4.
Output: [1,1,2,3,4,4]
Example 2:
Input:
list1 = []
list2 = []
Output: []
The merged list is empty.
Example 3:
Input:
list1 = []
list2 = [0]
Output: [0]
3. Approach – Iterative Merge with Dummy Head (Like Merge Step in Merge Sort):
This is similar to merging two sorted arrays, but using linked list nodes.
Intuition:
Use a dummy head node to simplify edge cases.
Maintain a pointer tail pointing to the last node of the merged list.
At each step, compare the current node values of list1 and list2:
Attach the node with the smaller value to tail.next.
Move that list’s pointer forward.
Move tail forward.
When one list is exhausted, attach the remaining part of the other list.
Since the input lists are already sorted, this produces a sorted merged list in one pass.
Algorithm (Step-by-Step):
Create a dummy node: dummy = new ListNode(0).
Initialize tail = dummy.
While both list1 and list2 are not null:
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
Move tail = tail.next.
After the loop, one of list1 or list2 is null:
Attach the non-null list:
tail.next = list1 if list1 not null
otherwise tail.next = list2
Return dummy.next as the head of the merged list.
Pseudo-code:
Let:
m = length of list1
n = length of list2
Then:
Time: O(m + n) (each node visited once)
Space: O(1) extra (we just rearrange pointers)
4. Java code:
5. C code:
6. C++ code:
7. Python code:
8. JavaScript code:






Comments
Post a Comment