1의자리부터 한 자리씩 링크드리스트에 저장되어있는 2수를 합한 것을 링크드 리스트에 더해서 반환하라.
ex) 123 + 456 = 579
3-2-1
첫번째 링크드 리스트 N
두번째 링크드 리스트 M
Worst N+1
O(Max(N,M))
Worst N + M + Max(N,M) + 1
O(Max(N,M))
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
first = l1
second = l2
carry = 0
answer = ListNode()
cur = answer
val1 = first.val
val2 = second.val
while True:
summation = val1 + val2 + carry
if summation >= 10:
carry = 1
summation = summation % 10
else:
carry = 0
#make new node to store the summation
cur.val = summation
#escape condition
if first.next == None and second.next == None and carry == 0:
break
if first.next != None:
first = first.next
val1 = first.val
else:
val1 = 0
if second.next != None:
second = second.next
val2 = second.val
else:
val2 = 0
#change cur to next node
cur.next = ListNode()
cur = cur.next
#while end
return answer
잘못된 내용에 대한 피드백 환영 합니다