Python中的循环链表
我在用Python实现一个循环链表的添加功能时遇到了问题。我有一个头指针,它应该指向一个节点,但每次我往列表里添加东西时,头指针总是变成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)
2 个回答
0
这个问题很好解决!在你的添加函数里,你把新的头节点赋值给了 head
变量——这个变量只在函数内部有效,函数结束后就消失了!
你需要把值赋给 self.head
,也就是当前实例的属性。
补充一下:当你写 head = self.head
时,其实是让它们都指向同一个对象。但是它们是两个独立的引用:无论它们指向的东西是否相同,改变一个不会影响另一个。
1
你只是在你的 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