【发布时间】:2018-04-01 05:39:13
【问题描述】:
我是这样定义循环链表的。
class Link(object):
def __init__ (self, data, next = None):
self.data = data
self.next = next
class CircularList(object):
def __init__ ( self ):
self.first = Link(None, None)
self.first.next = self.first
def insert_first ( self, item ):
new_link = Link(item)
new_link.next = self.first
self.first = new_link
def __iter__(self):
current = self.first
first = current
while current.next != first:
yield current
current = current.next
def __str__(self):
return str([Link.data for Link in self])
def __repr__(self):
return self.__str__()
然后我将项目插入到我的列表中
a = CircularList()
a.insert_first(4)
a.insert_first(5)
我想要一个我的循环列表的字符串表示,但看起来__iter__() 正在无限循环。我可以正确定义我的迭代器,并获得正确的字符串表示吗?
【问题讨论】:
-
将
__iter__中的first = current替换为first = self.first是否有效? -
@ndmeiri 不,它不起作用
-
您的
insert_first方法不正确——您没有正确更新指针。我建议采取一些样本案例,在纸上追踪它们并验证它确实不起作用。 -
@juanpa.arrivillaga 对不起,我对面向对象编程真的很陌生,无法理解你在说什么......
标签: python oop linked-list iterator circular-list