我已经像这样通过循环链接列表定义。
20014860486000000000000000008880
我将项目插入我的列表
20014860486000000000000000019980
我希望有一个循环列表的字符串表示,但看起来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__()
无限循环。我可以正确定义我的迭代器,并获得正确的字符串表示吗?
答案 0 :(得分:1)
我打破了台阶。
首先,我将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__()