python - while 循环中的链接节点。(将 LeetCode 中的两个数字相加)
问题描述
下面是 LeetCode 上 addTwoNumbers 链接节点列表问题的答案。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode(0)
temp = result
carry = 0
while l1 or l2 or carry:
val1 = (l1.val if l1 else 0)
val2 = (l2.val if l2 else 0)
carry, out = divmod(val1+val2 + carry, 10)
temp.next = ListNode(out)
temp = temp.next
l1 = (l1.next if l1 else None)
l2 = (l2.next if l2 else None)
return result.next
我很难理解如何
result = ListNode(0)
temp = result
在while循环之外和
temp.next = ListNode(out)
temp = temp.next
在while循环内部存储链接的节点。
我觉得代码应该result.next
保持不变,因为result
在 while 循环中从未调用过,但显然情况并非如此。
解决方案
推荐阅读
- ios - 打开操作表后如何删除 UIToolbar 下方的空白区域?
- triggers - 删除触发器导致删除集 Null 上的 FK 出现问题并导致 ORA-03113
- c++ - C++ 混淆宏
- javascript - 反应多重加载状态
- android - 用于 android 的 Ionic 4 硬件后退按钮在导航时无法在其他页面上运行
- python - 如何同时get.dummies和count
- nativescript - (Nativescript + Google Maps SDK)折线渐变颜色
- arrays - 值错误:使用序列(数组)设置数组元素
- html - 如何为下降线的部分着色?
- pine-script - 如何将形状垂直放置在条形上方 5 次?