Difficulty: 🟢 Easy
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a 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: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = []
Output: []
Example 3:
Input: list1 = [], list2 = [0]
Output: [0]
- The number of nodes in both lists is in the range
[0, 50]
. 100 <= Node.val <= 100
- Both
list1
andlist2
are sorted in non-decreasing order.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
root = ListNode()
temp = root
while list1 and list2:
if list1.val <= list2.val:
temp.next = list1
list1 = list1.next
else:
temp.next = list2
list2 = list2.next
temp = temp.next
temp.next = list1 if list1 else list2
return root.next
The given solution uses a iterative approach to merge the two sorted linked lists, list1
and list2
, into a single sorted list.
The algorithm works as follows:
- Create a new linked list with a dummy node as the root to keep track of the merged list.
- Initialize a temporary pointer,
temp
, to the root. - Compare the values of the current nodes in
list1
andlist2
. - Append the smaller value node to the
temp.next
and move the corresponding pointer (list1
orlist2
) to the next node. - Move the
temp
pointer to the next node as well. - Repeat steps 3-5 until either
list1
orlist2
becomesNone
. - Append the remaining nodes of the non-empty list (
list1
orlist2
) to the end of the merged list. - Return the
root.next
as the head of the merged linked list.
The time complexity of this algorithm is O(n + m), where n
and m
are the lengths of list1
and list2
, respectively. The algorithm iterates through both lists once to merge them.
The space complexity of the algorithm is O(1) since it only uses a constant amount of extra space to create the merged list and update the pointers.
The given solution merges two sorted linked lists into a single sorted list by comparing the values of nodes and splicing them together. It has a time complexity of O(n + m) and a space complexity of O(1), making it an efficient solution for the problem at hand.
NB: If you want to get community points please suggest solutions in other languages as merge requests.