class Node(object):
"雙向鏈表節點"
def __init__(self,item):
self.item=item
self.next=None #後
self.prev=None #前
class doublelist(object):
"雙向鏈表"
def __init__(self):
self._head=None #頭節點
# is_empty() 鏈表是否爲空
def is_empty(self):
return self._head is None
# length() 鏈表長度
def length(self):
count=0
cur=self._head
while cur!=None:
count+=1
cur=cur.next
return count
#顯示輸出列表
def printlist(self):
cur=self._head
while cur!=None:
print(cur.item)
cur=cur.next
# add(item) 鏈表頭部添加
def add(self, item):
node = Node(item)
# 當鏈表爲空
if self.is_empty():
node.next=self._head
self._head=node
else:
node.next = self._head
self._head.prev = node
self._head = node
# append(item) 鏈表尾部添加
def append(self,item):
node = Node(item)
cur=self._head
if self.is_empty():
node.next=cur
self._head=node
else:
while cur.next!=None:
cur=cur.next
cur.next=node
node.prev=cur
# insert(pos, item) 指定位置添加
def insert(self,pos,item):
if not isinstance(pos,int):
raise TypeError
if pos>self.length():
print('超出列表長度')
return
if pos < 0:
raise IndexError
if pos==0:
"表頭添加"
self.add(item)
elif pos == self.length():
"表尾添加"
self.append(item)
else:
# 否則就是正常情況
node = Node(item)
cur = self._head
count=0
while count<pos:#插入地方得到前一個節點
count+=1
cur=cur.next
cur.prev.next = node
node.prev = cur.prev
node.next = cur
cur.prev = node
# remove(item) 刪除節點
def remove(self,item):
cur=self._head
if cur==None:
print("元素不存在")
return
# 當刪除的是第一個元素
if cur.item == item:
self._head = cur.next
return
while cur.item!=item:
cur=cur.next
if cur==None:
print("元素不存在")
return
if cur.next==None:
cur.prev.next=None
else:
cur.prev.next=cur.next
cur.next.prev=cur.prev
# search(item) 查找節點是否存在
def search(self,item):
cur=self._head
if cur==None:
print(False)
return
else:
while cur.item!=item:
cur=cur.next
if cur==None:
print(False)
return
print(True)
return
if __name__=="__main__":
d=doublelist()
d.insert(0,0)
d.insert(1,1)
d.insert(2, 2)
d.search(0)