21. Merge Two Sorted Lists
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.
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
d = ListNode()
p = d
while l1 and l2 :
if l1.val < l2.val :
p.next = l1
l1 = l1.next
else :
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next = l1
else :
p.next = l2
return d.next
Explaination :
Comments
Post a Comment