首页 > 解决方案 > 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 循环中从未调用过,但显然情况并非如此。

标签: pythonsingly-linked-list

解决方案


推荐阅读