【发布时间】:2022-01-24 13:56:18
【问题描述】:
我目前正在自学一些编程,我偶然发现了一个问题,要求您制作一个包含某个数字的数字的链表(从最后一个到第一个)。这是我编写的代码,我不知道为什么它不起作用。我创建了简单的节点类和一个 Number 类来保存我的列表。
class Node:
def __init__(self, x=None):
self.val = x
self.next = None
def __str__(self):
return str(self.val)
class Number:
def __init__(self):
self.first = None
def set(self, num):
for i in range(len(str(num))):
tail = Node(num % 10)
if i == 0:
head = tail
num //= 10
tail = tail.next
self.first = head
Set 函数是用来创建一个给定数字的列表,所以
n = Number()
n.set(123)
应该创建一个列表 3 -> 2 -> 1,但是当我尝试使用打印它时
def node_printer(head: Node):
while head is not None:
if head.next is not None:
print(str(head) + ", ", end="")
else:
print(head)
head = head.next
并调用 node_printer(n.first) 我得到 3 作为输出。
【问题讨论】:
-
tail = tail.next因为tail刚刚创建,所以tail.next是None。 -
那么下一次迭代不会将None设置为下一个节点?
-
没有链接。
tail.next始终是None。
标签: python list oop linked-list