题目介绍
难度中等
给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
- 每个链表中的节点数在范围
[1, 100]
内 0 <= Node.val <= 9
- 题目数据保证列表表示的数字不含前导零
解答
# 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]:
p1 = l1
p2 = l2
tail = l1
c = 0
while p1 is not None and p2 is not None:
val = p1.val + p2.val + c
if val > 9:
p1.val = val % 10
c = 1
else:
p1.val = val
c = 0
tail = p1
p1 = p1.next
p2 = p2.next
while p1 is not None:
val = p1.val + c
if val > 9:
p1.val = val % 10
c = 1
else:
p1.val = val
c = 0
tail = p1
p1 = p1.next
while p2 is not None:
val = p2.val + c
tail.next = ListNode()
tail = tail.next
p1 = tail
if val > 9:
p1.val = val % 10
c = 1
else:
p1.val = val
c = 0
p2 = p2.next
if c == 1:
tail.next = ListNode()
tail = tail.next
p1 = tail
p1.val = 1
return l1
标签:p2,p1,val,相加,next,tail,l1
From: https://www.cnblogs.com/crazypigf/p/17292649.html