class Solution:
def addTwoNumbers(self, head1, head2):
# 연결리스트를 리스트로 만들고 뒤집은 다음에 숫자로 변환
if not head1 and not head2:
return 0
def toList(head):
list = []
# 리스트로 만들고
while head:
list.append(head.val)
head = head.next
# 뒤집은 다음에
list.reverse()
# 숫자로 바꿔줌
return int(''.join(str(e) for e in list))
# 더한거 연결리스트로 만들어줌
def toLinkedLst(head, result):
while result // 10 > 0:
node = ListNode(None)
remainder = result % 10
result //= 10
node.val = remainder
head.next = node
head = head.next
# 애초에 합이 한 자리수거나 위에서 연결리스트 만들면 하나가 남으니까 여기서 만들어줘야함.
if result >= 0:
node = ListNode(None)
node.val = result
head.next = node
# 연결리스트를 뒤집힌 숫자로 변환함
left, right = toList(head1), toList(head2)
# 뒤집은거 더해줌
result = left + right
# 리턴할 헤드
head = ListNode(None)
start = head
toLinkedLst(head, result)
return start.next
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution2:
def reverseList(self, head1, head2):
# 올림수
carry = 0
head = ListNode(None)
start = head
# 더할게 남았거나 올림수가 남았으면 더해줘야함
while head1 or head2 or carry:
# 해당 자리수의 덧셈 결과 저장할 노드
node = ListNode(None)
sum = 0
if head1:
sum += head1.val
head1 = head1.next
if head2:
sum += head2.val
head2 = head2.next
if carry:
sum += carry
carry = sum // 10
node.val = sum % 10
head.next = node
head = head.next
return start.next
[문제]
https://leetcode.com/problems/add-two-numbers/submissions/