class Node(object):
def __init__(self,elem):
self.elem=elem
self.pre=None
self.next=None
class DoubleTowardSingleLink(object):
def __init__(self, node=None):
self.__head=node
def is_empty(self):
return self.__head is None
def length(self):
cur=self.__head
count=0
while cur!=None:
cur=cur.next
count+=1
return count
def travel(self):
if self.is_empty==True:
print("empty list")
else:
cur=self.__head
while cur!=None:
print(cur.elem,end=" ")
cur=cur.next
print("")
def add(self,item):
node=Node(item)
if self.is_empty():
self.__head=node
print("空")
else:
node.next=self.__head
node.next.pre=node
self.__head=node
print("有")
def append(self,item):
node=Node(item)
if self.is_empty():
self.__head=node
print("kong")
else:
cur=self.__head
while cur.next!=None:
cur=cur.next
#node.pre=cur
cur.next=node
node.pre=cur
print("you")
def insert(self,pos,item):
node=Node(item)
if pos<=0:
self.add(item)
elif pos>self.length()-1:
self.append(item)
else:
cur=self.__head
count=0
while count<pos-1:
cur=cur.next
count+=1
node.next=cur.next
cur.next.pre=node
node.pre=cur
cur.next=node
def travelrev(self):
cur=self.__head
while cur.next!=None:
cur=cur.next
print(cur.elem,end=" ")
cur=cur.pre
while cur!=None:
print(cur.elem,end=" ")
cur=cur.pre
print("")
def remove(self, item):
if self.is_empty():
print("empty list")
return
else:
cur=self.__head
count=0
while cur!=None:
if cur.elem==item:
if cur.pre==None and cur.next==None:
self.__head=None
return
elif cur.pre==None and cur.next!=None:
self.__head=cur.next
cur.next.pre=self.__head
return
elif cur.pre!=None and cur.next==None:
cur.pre.next=None
return
else:
cur.pre.next=cur.next
cur.next.pre=cur.pre
return
cur=cur.next
print("no such element")
def search(self,item):
if self.is_empty():
print("no such element")
return
else:
cur=self.__head
count=0
while cur!=None:
if cur.elem==item:
print(count)
return
cur=cur.next
count+=1
print("no such element")
return
s=DoubleTowardSingleLink()
print(s.length())
print(s.is_empty())
s.add(3)
s.travel()
s.append(5)
s.travel()
s.add(10)
s.add("s")
s.append("c")
s.append("z")
s.append("g")
s.travel()
s.insert(2,"m")
s.insert(5,"x")
s.insert(7,"d")
s.travel()
print("===========")
s.travelrev()
#s.remove(1)
python 双向单链表
最新推荐文章于 2022-10-22 15:07:03 发布
本文详细介绍了如何在Python中实现双向单链表的数据结构,包括节点定义、链表初始化、插入、删除、遍历等操作。通过实例代码解析了双向单链表的工作原理和优势。
摘要由CSDN通过智能技术生成