21. Merge Two Sorted Lists ๐
Last updated
Last updated
Difficulty: Easy
- Tags: Linked List
, Sorting
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 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
The number of nodes in both lists is in the range [0, 50]
.
-100 <= Node.val <= 100
Both list1
and list2
are sorted in non-decreasing order.
To merge the two sorted lists, we can use the following approach:
Create a dummy node to simplify edge cases, and use a pointer to track the current position.
Compare the values of nodes from both lists and attach the smaller node to the merged list.
Move the pointer in the respective list after attaching its node.
When one of the lists is exhausted, attach the remaining nodes from the other list.
Return the merged list starting from the node after the dummy.
Dummy Node:
A dummy node simplifies handling the head of the merged list by avoiding edge-case checks for the first node.
Comparison:
Compare the current nodes of list1
and list2
, and append the smaller node to the merged list.
Exhaustion of Lists:
If one of the lists is completely traversed, attach the remaining nodes of the other list.
O(n + m): We iterate through all nodes in both list1
(of size n
) and list2
(of size m
).
O(1): The solution is done in place with no additional data structures.
You can find the full solution here.