# 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]:
dummy = ListNode() # 哑节点,便于处理结果链表
current = dummy
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0 # 获取 l1 当前节点的值
val2 = l2.val if l2 else 0 # 获取 l2 当前节点的值
# 计算当前位的和与进位
total = val1 + val2 + carry
carry = total // 10 # 更新进位
current.next = ListNode(total % 10) # 创建新节点存储当前位的值
current = current.next # 移动到下一个节点
# 移动 l1 和 l2 指针
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next # 返回结果链表的头节点
python-leetcode-两数相加
最新推荐文章于 2025-08-11 15:06:51 发布