The concept is to create a third result Linked List, and keep track of a tail node. Using the same logic as the merge function in merge sort, we assign the smaller value to the tail. Don’t forget to increment the tail.
Once we reach the end of one of the lists, we can simply copy the rest of the other list.
classListNode:def__init__(self, val=0,next=None): self.val = val
self.next=nextclassSolution:defmergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode])-> Optional[ListNode]: c1 = list1
c2 = list2
res = ListNode() tail = res
# base caseif c1 isNone:return c2
elif c2 isNone:return c1
# similar to merge sortwhile c1 isnotNoneand c2 isnotNone:if c1.val > c2.val: tail.next= c2
c2 = c2.nextelse: tail.next= c1
c1 = c1.next tail = tail.next# copy over the rest since one list reached its endif c1 isNone: tail.next= c2
elif c2 isNone: tail.next= c1
return res.next