基本概念
双向链表既可以向前也可以向后,有两个指针。
双向链表的结点
class Node():
def __init__(self,elem):
self.pre=None
self.elem=elem
self.next=None
双向链表的结构和遍历
def length(self):
#链表长度
if self.is_empty():
return 0
count=0
cur=self.__head
while cur.next is not None:
count+=1
cur=cur.next
return count
def travel(self):
#遍历链表
if self.is_empty():
return
cur=self.__head
while cur.next is not None:
print(cur.elem)
cur=cur.next
print(cur.elem)
插入元素
头部
#头部
def add(self,item):
node=Node(item)
if self.is_empty():
self.__head=node
else:
node.next=self.__head
self.__head.pre=node#这里老师用的是node.next,我认为老师写错了
self.__head=node
尾部
#尾部
def append(self,item):
node=Node(item)
if self.is_empty():
self.__head = node
else:
cur=self.__head
while cur.next is not None:
cur=cur.next
cur.next=node
node.pre=cur.next
中间
def insert(self,pos,item):
if pos<=0:
self.add(item)
elif pos >self.length():
self.append(item)
else:
node=Node(item)
count=0
cur=self.__head
while count < (pos-1):
count+=1
cur=cur.next
cur.next.pre=node
node.next=cur.next
cur.next=node
node.pre-cur.next
删除元素
尤其要注意中间的删除
def remove(self,item):
cur=self.__head#当前指针
forward=None#前一个指针
while cur is not None:
if cur.elem==item:
if cur==self.__head:
self.__head=cur.next
else:
forward.next=cur.next
return
else:
forward=cur
cur=cur.next