# Definition for singly-linked list. class Node(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: #设置初始头节点 dummy = p = ListNode(None) #初始节点和初始化0 s = 0 #同时循环遍历两个链表 while l1 or l2 or s != 0: s += (l1.val if l1 else 0) + (l2.val if l2 else 0) #判断是否进位 p.next = ListNode(s % 10) #移动指针 p = p.next if l1: l1 = l1.next if l2: l2 = l2.next #更新是否进位(1 or 0) s = s // 10 return dummy.next