# 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]:
"""To merge two sorted linked list first have to create dummynode and made this node as tail """
dummy=ListNode()
tail=dummy
"""Now check the value in list1 and list2 if value of list 1 is smaller it should made as next to dummy tail else list2 value should made tail to dummy tail. after making now head node of list change to its next node"""
while list1 and list2:
if list1.val<list2.val:
tail.next=list1
list1=list1.next
else :
tail.next=list2
list2=list2.next
tail=tail.next
if list1:
tail.next=list1
elif list2:
tail.next=list2
return dummy.next
Comments
Post a Comment