代码
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
p1, p2 = l1, l2
c = 0
pre_p1 = None
while p1 and p2:
tmp = p1.val + p2.val + c
p1.val = tmp % 10
c = tmp // 10
pre_p1, p1, p2 = p1, p1.next, p2.next
if p2:
pre_p1.next = p2
p1 = p2
while p1 and c:
tmp = p1.val + c
p1.val = tmp % 10
c = tmp // 10
pre_p1, p1 = p1, p1.next
if c:
p1 = ListNode(1)
pre_p1.next = p1
return l1
[题目源于leetcode Hot_100]