gpt4 book ai didi

python - python中的循环链表

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:08 24 4
gpt4 key购买 nike

我被困在Python中实现循环链​​表的add函数。我有一个头指针,它应该是对节点的引用,但每次我向列表中添加一些内容时,头总是 None 。这是我到目前为止的代码:

class CircleList():

__slots__ = ('head', 'size')

def __init__(self):
self.head = None
self.size = 0

def __str__(self):
result = "<"
node = self.head
count = self.size
while count != 0:
result = result + str(node.data)
if count != 1:
result = result + ", "
node = node.next
count -= 1
result = result + ">"
return result

def add(self, element):
head = self.head
print(head)
size = self.size
if head == None:
head = Node(element, None)
head.next = head
else:
cursor = head
while cursor.next != head:
cursor = cursor.next
temp = Node(element, head)
cursor.next = temp
size += 1


class Node():
__slots__ = ('data','next')

def __init__(self, data, next):
self.data = data
self.next = next

这是驱动程序:

stream = open('data.txt', 'r')

circlelist = CircleList()

for name in stream
circlelist.add(name)

print(circlelist)

最佳答案

您只需将新节点分配给 add() 方法中的本地 head 变量,而不是实际的 CircleList 实例成员。

您可能想做类似的事情:

def add(self, element):
head = self.head
print(head)
size = self.size
if head is None:
self.head = head = Node(element, None) # Also set the instance member.
head.next = head

关于python - python中的循环链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4360050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com