创建
class Node:def __init__(self,data):# 数据域self.data = data# 链接域self.next = Noneclass LinkList:def __init__(self,):# 初始化头节点self.head = None# 记录链表的长度self.size = 0
增加
#头插def insert_head(self,value):# 创建新节点node = Node(value)q = self.head# 头插while q:q = q.nextnode.next = self.headself.head = node# 插入成功,链表长度自增self.size += 1#尾插def insert_rear(self,value):# 创建新结点node = Node(value)# 判空,若为空则在头节点插入if self.is_empty():self.head = nodeelse:# 不为空则遍历到最后一个结点插入新结点p = self.head# 遍历到结点链接域为None说明到达最后一个结点while p.next:p = p.nextp.next = node# 添加成功,链表长度自增self.size += 1# 遍历链表def show(self):# 判空if self.is_empty():print("遍历失败")returnelse:# 创建临时变量q = self.headwhile q:print(f"{q.data}",end=" ")q = q.nextprint()
#任意位置插入def insert_any_index(self,value,index):# 判断位置是否合理if 1>index or index >self.size+1:print("插入失败")else:# 若为第一个元素,则使用头插法if index == 1:self.insert_head(value)else:node = Node(value)p = self.headi = 1# 将p指向要插入位置的前一个结点while i<index-1:p = p.nexti += 1# 新结点的链接域指向前结点的下链接域,前结点的链接域指向新结点dnode.next = p.nextp.next = nodeself.size += 1
删除
def delete_head(self):if self.is_empty():print("删除失败")returnelse:self.head = self.head.nextself.size -= 1def delete_rear(self):if self.is_empty():print("删除失败")returnelif self.size == 1:self.head =Noneself.size -= 1else:p = self.headwhile p.next.next :p = p.nextp.next = p.next.nextself.size -= 1def any_index_delete(self,index):if self.is_empty():print("删除失败")returnelse:if index == 1:self.delete_head()returni = 1p = self.headwhile i<index-1:p = p.nexti+=1p.next = p.next.nextself.size -= 1
查找与修改
def revise_index(self,index,value):if self.is_empty() or not 1<=index<=self.size:print("修改失败")returnelse:i = 1p = self.headwhile i<index:p = p.nexti += 1p.data = valuedef find_index(self,value):if self.is_empty():print("查找失败")returni = 1q = self.headwhile i<self.size:if q.data == value:print(f"查找成功,你要的数据在第{i}个结点")return ii += 1q = q.nextelse:print("查找失败")def revise_value(self,value,n_value):self.revise_index(self.find_index(value),n_value)return
转置
def transposition(self):if self.is_empty():print("失败")p = self.headt = self.headwhile p.next:t = p.nextp.next = t.nextt.next = self.headself.head = t