class MyLinkedList:
"""
双向链表
"""
class Node:
def __init__(self, data, prev=None, next=None):
self.data = data
self.prev = prev
self.next = next
def __init__(self):
"""
有头的双向链表
"""
self.__size = 0
self._head = self.Node("head")
self._tail = self.Node("tail")
self._head.next = self._tail
self._tail.prev = self._head
@property
def size(self):
return self.__size
def append(self, data):
node = self.Node(data)
# 保存尾结节的前一个节点
prev = self._tail.prev
# 关联前节点和新节点
prev.next = node
node.prev = prev
# 关联尾节点和新节点
self._tail.prev = node
node.next = self._tail
# 计数+1
self.__size += 1
def get(self, index):
if index >=0 and index <self.__size:
i = 0
node = self._head
while i<=index:
node = node.next
i += 1
return node
else:
raise IndexError
def __iter__(self):
"""
在调用for-in或iter()时,会执行此方法
:return:
"""
self.count = 0
return self
def __next__(self):
while self.count < self.__size:
node = self.get(self.count)
self.count += 1
return node
raise StopIteration
if __name__ == '__main__':
mll = MyLinkedList()
for x in range(3):
mll.append(f"data {x}")
print(mll.size)
# 使用for-in遍历迭代器
for i in mll:
print(i.data)
# 初始化迭代器
it = iter(mll)
while True:
try:
print(next(it).data)
except StopIteration:
break
python 链表 + 迭代器
最新推荐文章于 2020-10-07 11:16:31 发布