1.定义结点类
class Node:
def __init__(self, data=None,next=None,prev=None):
self.data = data
self.next = next
self.prev = prev
2.定义链表类
class DoublyLinkedList:
def __init__(self):
self.head = None
2.1.打印正向链表
def print_forward(self):
if self.head is None:
print("Linked list is empty")
return
itr = self.head
llstr = ''
while itr:
llstr += str(itr.data) + "-->"
itr = itr.next
print(llstr)
2.2.打印反向链表
def print_backward(self):
if self.head is None:
print("Linked list is empty")
return
last_node = self.get_last_node()
itr = last_node
llstr = ''
while itr:
llstr += itr.data + '-->'
itr = itr.prev
print("Link list in reverse:",llstr)
2.3.寻找链表最后一个结点
def get_last_node(self):
itr = self.head
while itr.next:
itr = itr.next
return itr
2.4.计算链表长度
def get_length(self):
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
2.5.链表首部插入元素
def insert_at_begining(self,data):
node = Node(data,self.head,None)
self.head.prev = node
self.head = node
2.6.链表尾部插入元素
def insert_at_end(self,data):
if self.head is None:
self.head = Node(data, None, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data,None,itr)
2.7.链表任意位置插入元素
def insert_at(self, index, data):
if index<0 or index>self.get_length():
raise Exception("Invalid Index")
if index == 0:
self.insert_at_begining(data)
return
count = 0
itr = self.head
while itr:
if count == index-1:
node = Node(data, itr.next, itr)
if node.next:
node.next.prev = node
itr.next = node
break
itr = itr.next
count += 1
2.8.链表任意位置删除元素
def remove_at(self, index, data):
if index<0 or index>=self.get_length():
raise Exception("Invalid Index")
if index==0:
self.head = self.head.next
self.head.prev = None
return
count = 0
itr = self.head
while itr:
if count == index:
itr.prev.next = itr.next
if itr.next:
itr.next.prev = itr.prev
break
itr = itr.next
count += 1
2.9.链表中插入一堆元素
def insert_values(self,data_list):
self.head = None
for data in data_list:
self.insert_at_end(data)
3.测试
ll = DoublyLinkedList()
ll.insert_values(["banana","mango","grapes","orange"])
ll.print_forward()
ll.print_backward()
ll.insert_at_end("figs")
ll.print_forward()
ll.print_backward()
ll.insert_at(0,"jackfruit")
ll.print_forward()
ll.insert_at(6,"dates")
ll.print_forward()
ll.insert_at(2,"kiwi")
ll.print_forward()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cc1bc485b8a34ae251cd7ab23d7a093b.png)