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.
list1
and list2
simultaneously:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(list1: ListNode, list2: ListNode) -> ListNode:
# Initialize dummy node and current pointer
dummy = ListNode()
current = dummy
# Traverse both lists
while list1 and list2:
if list1.val < list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next
# Attach the remaining nodes, if any
if list1:
current.next = list1
if list2:
current.next = list2
# Return the merged list starting from the node next to dummy
return dummy.next
list1
and (m) is the length of list2
.This solution is optimal for merging two sorted linked lists and ensures that the merged linked list remains sorted.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?