문제 바로가기
Recursion
class Solution:
def __init__(self):
self.mergedList = ListNode()
self.head = self.mergedList
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not (l1 or l2):
return self.mergedList.next
if not l1:
self.head.next = l2
return self.mergedList.next
if not l2:
self.head.next = l1
return self.mergedList.next
if l1.val < l2.val:
self.head.next = l1
l1 = l1.next
else:
self.head.next = l2
l2 = l2.next
self.head = self.head.next
return self.mergeTwoLists(l1, l2)
Loop
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
mergedList = ListNode()
head = mergedList
while l1 and l2:
if l1.val <= l2.val:
head.next = l1
l1 = l1.next
else:
head.next = l2
l2 = l2.next
head = head.next
head.next = l1 if l1 else l2
return mergedList.next