class DoubleNode():
def __init__(self,item):
self.elem = item
self.pre = None
self.next = None
class DoubleLinkNode():
def __init__(self,head=None):
self.__head = head
self.__head.next = None
def isempty(self):
return self.__head.next == None
def length(self):
count = 0
p = self.__head.next
while p!=None:
count += 1
p=p.next
return count
def travel(self):
if self.isempty():
print("链表是空的")
return
else:
p = self.__head.next
while p!=None:
print(p.elem,end=" ")
p = p.next
# 头插法创建双向链表
def add(self,item):
node = DoubleNode(item)
if self.isempty():
self.__head.next = node
node.pre = self.__head
else:
p = self.__head
node.next = p.next
p.next.pre = node
p.next = node
node.pre = p
def append(self,item):
node = DoubleNode(item)
p = self.__head
while p.next!=None:
p = p.next
p.next = node
node.pre = p
# 在某一位置插入节点
def insert(self,pos,item):
if pos<=0 :
print("超出范围,无法插入")
return
elif pos>=self.length():
self.append(item)
else:
node = DoubleNode(item)
index = 0
p = self.__head.next
while p!=None:
index += 1
if index==pos:
node.next = p.next
node.pre = p
p.next.pre = node
p.next = node
p=p.next
# 根据索引删除
def remove(self,pos):
if pos<=0 or pos>self.length():
print()
print("超出范围,无法删除")
return
else:
p = self.__head.next
count = 0
while p!=None:
count += 1
# 解决删除最后一个节点的特殊情况
if pos==self.length()and count==self.length():
p.pre.next = None
break
# 其余情况
elif count==pos:
p.pre.next = p.next
p.next.pre = p.pre
break
else:
p = p.next
# 查找指定位置节点
def search(self,pos):
if pos<=0 or pos>self.length():
print("该位置没有节点")
else:
p = self.__head
count = 0
while p.next!=None:
count +=1
if count==pos:
return p.next.elem
p = p.next
# 测试
if __name__=='__main__':
head = DoubleNode(0)
double = DoubleLinkNode(head)
# 头插法测试
double.add(1)
double.add(2)
# 尾插法测试
double.append(3)
double.append(4)
print(double.isempty())
# 插入节点测试
double.insert(5, 5)
print(double.length())
double.travel()
# 删除节点测试
double.remove(10)
print()
print("删除节点后遍历")
double.travel()
print()
print(double.search(1))
print(double.search(3))
print(double.search(5))
python数据结构之双向链表
最新推荐文章于 2022-08-23 20:23:16 发布