Skip to main content

445. Add Two Numbers II

https://leetcode.com/problems/add-two-numbers-ii/

Python

# 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]:
if not l1 and not l2:
return ListNode(val=0)
stack1, stack2 = [], []
cur1, cur2 = l1, l2

while cur1:
stack1.append(cur1.val)
cur1 = cur1.next

while cur2:
stack2.append(cur2.val)
cur2 = cur2.next

new_head = None
carry = 0
while stack1 or stack2 or carry:
num1 = stack1.pop() if stack1 else 0
num2 = stack2.pop() if stack2 else 0

total = num1 + num2 + carry
carry = total // 10

new_node = ListNode(total % 10)
new_node.next = new_head
new_head = new_node

return new_head