我被困在python中實現了循環鏈表的add函數。我有一個頭指針應該是一個節點的引用,但是每次我向列表中添加一些東西時,頭總是無。下面是代碼我迄今:python中的循環鏈表
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)
爲什麼你實現它這樣的原因嗎?它不完全是pythonic,你可以輕鬆想出一個更加優雅的版本來擴展`list`,提供像`__getitem__`這樣的元方法並使用索引。這也消除了對多餘的Node類的需求。另外,我建議堅持列表中衆所周知的界面。 – 2010-12-05 17:23:37