The βMerge Two Sorted Listsβ problem asks us to merge two sorted singly linked lists, list1
and list2
, into one new sorted linked list. The goal is to preserve the non-decreasing order of elements and return the head of the newly merged list.
Example:
list1 = 1 β 2 β 4
, list2 = 1 β 3 β 4
1 β 1 β 2 β 3 β 4 β 4
Merging two sorted lists is a foundational concept used in algorithms such as merge sort and in real-world scenarios involving sorted streams of data. It reinforces pointer manipulation in linked lists and teaches how to maintain sorted order efficiently.
The most effective way to merge two sorted lists is to use a dummy node to simplify edge cases and a current pointer to build the merged list incrementally.
current
pointer pointing to the dummy node.list1
and list2
are non-null:
list1
and list2
.current.next
.current
forward and also advance the list from which the node was taken.current.next
.dummy.next
as the head of the merged list.
Inputs: list1 = 1 β 2 β 4
, list2 = 1 β 3 β 4
Execution:
list2
Result: 1 β 1 β 2 β 3 β 4 β 4
Time Complexity: O(n + m), where n
is the length of list1
and m
is the length of list2
. Each node is visited exactly once.
Space Complexity: O(1) auxiliary space, since we are not creating any new nodes (just reusing and rearranging pointers).
The βMerge Two Sorted Listsβ problem is a classic example of how to manipulate linked lists efficiently using pointers. By reusing existing nodes and carefully adjusting links, we can produce a clean, sorted list with no additional space. This problem forms the backbone of more complex algorithms and teaches critical low-level manipulation skills.