Description
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
給定兩個非空鍊錶,分別表示兩個非負整數。數字以逆序存儲,每個節點包含一位數字。將兩個數字相加,並以鍊錶形式返回和。
You may assume the two numbers do not contain any leading zero, except the number 0 itself.您可以假設這兩個數字不包含任何前導零,除了數字 0 本身。
Solution

# 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]:
dummyhead = ListNode(0)
current = dummyhead
carry = 0
while l1 or l2 or carry:
l1val = l1.val if l1 else 0
l2val = l2.val if l2 else 0
sum = l1val + l2val + carry
carry = sum // 10
newNode = ListNode(sum%10)
current.next = newNode
current = newNode
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummyhead.next
如果對 linked list 有任何疑問可以參考這篇