在while循环中链接的节点。 (从LeetCode中添加两个数字)

时间:2019-12-04 05:11:35

标签: python singly-linked-list

下面是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循环中被调用,但是显然并非如此。

0 个答案:

没有答案