[英]Python linked list: Connect head with linked list node
我正在尝试将数字转换为链接列表(例如,将617转换为7-> 1-> 6)
这是我的代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
# write your code here
num_1 = num_2 = 0
counter = 1
# convert each linked list to an integer
while l1 != None:
num_1 += l1.val * counter
l1 = l1.next
counter *= 10
# reset counter
counter = 1
while l2 != None:
num_2 += l2.val * counter
l2 = l2.next
counter *= 10
# perform the addition
my_sum = num_1 + num_2
# convert the sum back to a linked list
# initialize head
sum_head = ListNode(my_sum % 10)
sum_node = sum_head
my_sum //= 10
while my_sum != 0:
sum_node.next = ListNode(my_sum % 10)
sum_node = sum_node.next
my_sum //= 10
# return the the linked list
return sum_head
我编写了这一部分,这部分代码起作用了。 我只是不明白为什么“ sum_head”能够链接到第二个节点“ sum_node”。
这是Python中的示例:
a = <Object>
b = a
b只是对a的引用,对吗?
假设将617转换为7-> 1-> 6。 按照我的代码,头是7,其余的链表是7-> 1-> 6。 机头如何知道下一个节点是1?
前两个变量不是链表中的“链表”。 它们是同一对象。 如果将其替换为等效表达式,则可能会更清楚:
sum_head = ListNode(my_sum % 10)
sum_node = sum_head
# ==
sum_node = sum_head = ListNode(my_sum % 10)
# So: sum_node.next is sum_head.next
为什么我们需要两个指向同一对象的变量? 因为在以下几行中,我们更改了sum_node指向的内容。 它将成为先前对象的.next
。 由于没有退回的方法,因此我们需要保留头部的引用以将其返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.