题目:
题解:
# 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]:
carry = 0
p = l1
q = l2
dummy = ListNode(0)
k = dummy
while p or q:
val1 = p.val if p else 0
val2 = q.val if q else 0
n = val1 + val2 + carry
carry = n // 10
res = n % 10
node = ListNode(res)
k.next = node
k = k.next
if p:
p = p.next
if q:
q = q.next
if carry:
node = ListNode(carry)
k.next = node
return dummy.next