Merge Two Sorted Lists easy
Problem Statement
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
Example 1
Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2
Input: list1 = [], list2 = [] Output: []
Steps
- Handle Empty Lists: If either
list1
orlist2
is null (empty), return the other list. - Create a Dummy Node: Create a dummy node to simplify the process of building the merged list. This dummy node will point to the head of the merged list.
- Initialize Pointers: Use pointers
tail
(initially pointing to the dummy node) andp1
,p2
(pointing to the heads oflist1
andlist2
respectively). - Iterate and Compare: While
p1
andp2
are not null, compare the values atp1
andp2
.- Append the smaller node to
tail
. Movetail
and the corresponding pointer (p1
orp2
) forward.
- Append the smaller node to
- Handle Remaining Nodes: After one list is exhausted, append the remaining nodes from the other list to
tail
. - Return the Merged List: Return the next node after the dummy node (which is the head of the merged list).
Explanation
The algorithm efficiently merges two sorted lists by iteratively comparing the heads of the remaining portions of each list. The use of a dummy node eliminates edge cases and simplifies the code by always having a valid tail
to append to. The time complexity is linear because we visit each node in both lists exactly once.
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// Handle empty lists
if (list1 == null) return list2;
if (list2 == null) return list1;
// Create a dummy node
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
// Initialize pointers
ListNode p1 = list1;
ListNode p2 = list2;
// Iterate and compare
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
tail.next = p1;
p1 = p1.next;
} else {
tail.next = p2;
p2 = p2.next;
}
tail = tail.next;
}
// Handle remaining nodes
tail.next = (p1 != null) ? p1 : p2;
// Return the merged list
return dummy.next;
}
}
Complexity
- Time Complexity: O(m + n), where 'm' and 'n' are the lengths of
list1
andlist2
respectively. We iterate through each list once. - Space Complexity: O(1). We use a constant amount of extra space regardless of the input size. The space used by the merged list itself is not considered in space complexity analysis.