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)