源码
#封装普通节点的类
class Node:
#构造函数,定义结点的属性
def __init__(self, data):
self.data = data #普通结点的数据域
self.next = None #普通结点的连接域,刚构造的结点该位置域为空
#封装链表的类(封装头节点)
class Linklist:
def __init__(self, node=None):
self.size = 0 #头结点的数据域为0 链表的长度为0
self.head = node #头结点的连接域指向None
#判空
def is_empty(self):
return not self.head
# return self.size==0 或者判断长度是否为零
#头插
def add_head(self, value):
#创建一个新的结点
node = Node(value)
node.next = self.head
self.head = node
self.size += 1
#尾插
def add_tail(self, value):
#创建一个结点node
node = Node(value)
#找最后一个结点
# q = self.head
# i=1
# while i<self.size:
# q=q.next
# i+=1
# q.next=node
# self.size+=1
#第二种方法
q = self.head
while q.next:
q = q.next
q.next = node
self.size += 1
#第三种
# while True:
# q=q.next
# if not q.next:
# q.next = node
# self.size+=1
# break
#任意位置插
def add_any(self, id, value):
node = Node(value)
if id == 1:
self.add_head(value)
elif id == self.size+1:
self.add_tail(value)
elif id>self.size+1:
print('插入失败')
return
else:
q = self.head
i = 1
while i < id - 1:
q = q.next
i += 1
node.next = q.next
q.next = node
self.size += 1
#头删
def del_head(self):
self.head = self.head.next
self.size -= 1
#尾删
def del_tail(self):
if self.size==1:
self.head=None
else:
q = self.head
for i in range(self.size - 2):
q = q.next
q.next = None
self.size -= 1
#任意位置删
def del_any(self,id):
if id==1:
self.del_head()
else:
q = self.head
for i in range(id - 2):
q = q.next
q.next = q.next.next
self.size -= 1
#遍历
def show(self):
#判空
if self.is_empty():
print('遍历失败')
return
else:
q = self.head
while q:
print(q.data, end=' ')
q = q.next
print()
#任意位置修改
def change_id(self,id,value):
if id==1:
self.head.data=value
else:
q=self.head
for i in range(id-1):
q=q.next
q.data=value
#按值修改
def change_value(self,value,new_value):
q=self.head
while q:
if q.data==value:
q.data=new_value
break
q=q.next
#按值查找返回位置
def return_id(self,value):
q=self.head
i=1
while q:
if q.data==value:
print(i)
return
q=q.next
i+=1
else:
print('没有该值')
#链表的翻转
def reverse(self):
prev = None
current = self.head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.head = prev
#测试
if __name__ == '__main__':
#创建链表
linklist = Linklist()
linklist.add_head(10)
linklist.add_head(20)
linklist.add_head(30)
linklist.add_head(40)
linklist.add_head(50)
linklist.add_tail(50)
# linklist.add_any(8, 100)
# linklist.del_head()
linklist.del_tail()
linklist.del_any(2)
linklist.change_id(2,80)
linklist.change_value(80,40)
linklist.return_id(40)
linklist.reverse()
#遍历
linklist.show()