Merge Two Sorted Lists
Algorithm/LinkedList
Intuition
The task is to merge two sorted linked lists into a single sorted linked list. Since both input lists are already sorted, we can efficiently merge them by comparing their current nodes step-by-step and building a new list in sorted order.
Approach
Below is the step-by-step breakdown of the approach:
-
Initialize a Dummy Node:
- Create a
dummyHead
node, which serves as the starting point for our result list. - Use a
current
pointer to track the end of the merged list as we build it.
- Create a
-
Merge Lists:
- Traverse through both lists until one becomes empty:
- Compare the values at the current nodes of
list1
andlist2
. - Attach the smaller node to
current.next
, and move that list's pointer forward. - Advance
current
tocurrent.next
to continue building the merged list.
-
Attach Remaining Nodes:
- Once we reach the end of one list, directly link
current.next
to the remaining non-empty list, as it's already sorted.
- Once we reach the end of one list, directly link
-
Return Result:
- Return
dummyHead.next
, which points to the head of the merged list.
- Return
Complexity
- Time complexity: , where m and n are the lengths of
list1
andlist2
. We iterate through both lists once. - Space complexity: for the merged list since we're modifying pointers directly, resulting in an in-place merge.