# 预定义类型
from typing import Optional
class ListNode:
val = 0
next = None
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]:
bEndL1 = False
bEndL2 = False
nAdd = 0
ret = ListNode()
head = ret
i = 0
while (l1 != None or l2 != None):
if l1 == None:
bEndL1 = True
if l2 == None:
bEndL2 = True
# 计算当前节点值
if not bEndL1 and not bEndL2:
val = l1.val + l2.val + nAdd
elif bEndL1:
val = l2.val + nAdd
elif bEndL2:
val = l1.val + nAdd
# 计算进位
if val >= 10:
val -= 10
nAdd = 1
else:
nAdd = 0
# 构建节点
if 0 == i:
ret.val = val
else:
ret.next = ListNode(val)
ret = ret.next
# 递增
i += 1
if l1 != None:
l1 = l1.next
if l2 != None:
l2 = l2.next
# 补进位
if nAdd == 1:
ret.next = ListNode(1)
# 输出结果
return head
# 测试
l1 = ListNode(9)
temp = l1
for i in range(0, 1):
temp.next = ListNode(9)
temp = temp.next
l2 = ListNode(9)
temp = l2
for i in range(0, 2):
temp.next = ListNode(9)
temp = temp.next
print(l1)
print(l2)
obj = Solution()
ret = obj.addTwoNumbers(l1, l2)
while ret != None:
print(f"{ret.val} ")
ret = ret.next
Leetcode.02. 两数相加
最新推荐文章于 2024-11-10 14:06:08 发布