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
defsize
(self)
:return self.__size
def(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 +=
1def
get(self, index)
:if index >=
0and index i =
0 node = self._head
while i<=index:
node = node.
next
i +=
1return node
else
:raise indexerror
def__iter__
(self)
:"""
在呼叫for-in或iter()時,會執行此方法
:return:
"""self.count =
0return self
def__next__
(self)
:while self.count < self.__size:
node = self.get(self.count)
self.count +=
1return node
raise stopiteration
if __name__ ==
'__main__'
: mll = mylinkedlist(
)for x in
range(3
):)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
鍊錶以及鍊錶的迭代器
list.h pragma once template class list template class listiterator 鍊錶節點 template class listnode template class list template class listiterator 用來判斷鍊錶...
STL 鍊錶和迭代器
include include include include include include include include 迭代器 空間配置器 using namespace std 鍊錶實現 namespace my 構造 template class t1,class t2 void con...
反轉鍊錶(迭代) 基於python
輸入乙個鍊錶,反轉鍊錶後,輸出新鍊錶的表頭。反轉鍊錶是面試的基礎題,掌握是很有必要的。我們採用迭代思想進行鍊錶反轉 首先我們定義三個指標,分別表示前乙個節點pre,當前節點cur,中間節點temp 每次迴圈時使得當前節點指向前一節點,然後節點後移進行下一反轉。coding utf 8 class l...