"""雙向鍊錶節點
"""def
__init__
(self, item):
self.item =item
self.next =none
self.prev =none
class
dlinklist(object):
def__init__
(self):
self.head =none
defis_empty(self):
return self.head is
none
deflength(self):
"""返回鍊錶的長度
"""cur =self.head
count =0
while cur is
notnone:
count += 1cur =cur.next
return
count
deftr**el(self):
"""遍歷鍊錶
"""cur =self.head
while cur is
notnone:
(cur.item)
cur =cur.next
print("
遍歷完了")
defadd(self, item):
node =node(item)
ifself.is_empty():
self.head =node
else
: node.next =self.head
self.head.prev =node
self.head =node
def
"""尾部插入元素
"""node =node(item)
ifself.is_empty():
self.head =node
else
: cur =self.head
while cur.next is
notnone:
cur =cur.next
cur.next =node
node.prev =cur
defsearch(self, item):
cur =self.head
while cur is
notnone:
if cur.item ==item:
return
true
cur =cur.next
return
false
definsert(self, pos, item):
"""在指定位置新增節點
"""if pos <=0:
self.add(item)
elif pos > (self.length()-1):
else
: node =node(item)
cur =self.head
count =0
#移動到指定位置的前乙個位置
while count < (pos-1):
count += 1cur =cur.next
#先把node的關係設定好
node.prev =cur
node.next =cur.next
#再配置cur的關係
cur.next.prev =node
cur.next =node
defremove(self, item):
"""刪除元素,元素不存在不報錯
"""if
self.is_empty():
return
else
: cur =self.head
#如果首節點是要刪除的元素
if cur.item ==item:
if cur.next is
none:
#如果鍊錶只有這乙個節點
self.head =none
else
:
#將第二個節點的prev設定為none
cur.next.prev =none
self.head =cur.next
return
#遍歷節點
while cur is
notnone:
if cur.item ==item:
cur.prev.next =cur.next
cur.next.prev =cur.prev
break
cur =cur.next
if__name__ == '
__main__':
lst1 =dlinklist()
lst1.add(1)
lst1.add(2)
lst1.insert(1, 4)
lst1.tr**el()
(lst1.is_empty())
lst1.remove(2)
lst1.tr**el()
lst1.remove(10)
lst1.tr**el()
雙向鍊錶的實現
實現雙向鍊錶(Python)
可以快速找到上 下節點,也可以快速去掉鍊錶中的某乙個節點。encoding utf 8 class node def init self,key,value self.key key self.value value self.prev none self.next none def str sel...
Python實現雙向鍊錶
class dwlinkedlist class node 結點類 用於存放數值以及前後指標 def init self,value,last,next none self.value value self.last last self.next next def init self 建立乙個結點 ...
雙向鍊錶實現
template class link link link pre null,link ne null void operator new size t void operator delete void ptr template link link freelist null template v...