我已经这样定义了循环链表。
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__()
正在无限循环。我可以正确定义迭代器,并获得正确的字符串表示形式吗?
最佳答案
我将分解步骤。
首先,我将 Link
重命名为 Node
。
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
链接与节点不同 - 节点保存数据,链接将两个节点连接在一起。
接下来,CircularList
类需要进行一些更改。
__init__
将需要初始化一个空列表。这意味着根本没有节点。为了方便起见,我定义了 self.last
来极大地简化代码(注意,极大,你将会遇到困难否则)。
class CircularList(object):
def __init__(self):
self.first = self.last = None
对于insert_first
,您需要处理列表为空时的特殊情况以及一般情况。相应地更新 self.first
和 self.last
。
def insert_first(self, item):
if self.first is None:
self.first = self.last = Node(item)
self.first.next = self.first
else:
self.first = Node(item, self.first)
self.last.next = self.first
你的__iter__
方法也应该以同样的方式响应。内嵌评论。
def __iter__(self):
# corner case - yield empty list
if not self.first:
yield []
else:
# start by yielding the head node
yield self.first
cur = self.first.next
# iterate as long as you do not see the head node again
while cur is not self.first:
yield cur
cur = cur.next
其他方法保持不变。测试代码:
a = CircularList()
for i in [5, 4, 3, 2, 1]:
a.insert_first(i)
print(a)
[1, 2, 3, 4, 5]
<小时/>
完整代码列表
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class CircularList(object):
def __init__(self):
self.first = self.last = None
def insert_first(self, item):
if self.first is None:
self.first = self.last = Node(item)
self.first.next = self.first
else:
self.first = Node(item, self.first)
self.last.next = self.first
def __iter__(self):
if not self.first:
yield []
else:
yield self.first
cur = self.first.next
while cur is not self.first:
yield cur
cur = cur.next
def __str__(self):
return str([Link.data for Link in self])
def __repr__(self):
return self.__str__()
关于python - 循环链表代码陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49595144/