class Node:
"""链表的节点的结构"""
def __init__(self,data):
self.data=data #数据
self.next=None #下一个结点指针
return
def has_value(self,value):
"""判断节点值是否为参数value"""
if self.data==value:
return True
else:
return False
class singlelink:
"""单链表数据结构"""
def __init__(self):
self.head=None #头节点
self.tail=None #尾节点
self.length=0 #链表长度
return
def isempty(self):
"""判断链表是否为空链表"""
return self.length==0
def add_node(self,item):
"""链表尾部添加节点"""
if not isinstance(item,Node): #如果参数不是节点类型
item=Node(item) #创建节点
if self.head is None: #如果头节点为空,直接让头指向新节点
self.head=item
self.tail=item
else:
self.tail.next=item #尾部添加
self.tail=item
self.length+=1
return
def insert_node(self,index,data):
"""链表插入节点,参数为:index位置,data数据"""
if self.isempty(): #链表若空
print("link is empty,operation failed.")
return
if index<0 or index>=self.length: #索引若越界
print("error.out of index.")
item=Node(data) #建立新节点
if index==0: #头部插入
item.next=self.head #新节点next指向头
self.head=item #更新头为新节点
self.length+=1 #链表长度加1
return
j=0
curr=self.head #当前指针
pre=self.head #当前指针的前一位
while curr.next and j<index: #非尾结点且未找到要插入位置index
pre=curr
curr=curr.next #更新指针为下一位
j+=1
if j==index: #找到对应的位置,此时curr指针在目标位置
#item.next=curr
#pre.next=item
pre.next=item
item.next=curr #思考两者顺序是否能颠倒---可以
self.length+=1
def delete_node_byid(self,item_id):
"""按给出的id值,删除某节点"""
id=1
curr=self.head
pre=self.head
while curr is not None:
if id==item_id: #找到了要删除的节点位置
if pre is not None:
pre.next=curr.next
else: #pre不存在,小于两个节点的情况
self.head=curr.next
return
pre=curr
curr=curr.next
id+=1
self.length-=1 #长度减一
return
def find_node(self,value):
"""找出链表中是否存在value值,打印其位置(非索引)"""
curr=self.head
id=1
result=[]
while curr is not None:
if curr.has_value(value):
result.append(id) #如果有value,位置加入结果集
curr=curr.next
id+=1
return result
def print_link(self):
"""遍历打印链表值"""
curr=self.head
while curr is not None:
print(curr.data)
curr=curr.next
return
Node1=Node(1)
Node2=Node(2)
Node3=Node(3)
Node4=Node(4)
Node5=Node(5)
link=singlelink()
for node in[Node1,Node2,Node3,Node4,Node5]:
link.add_node(node)
link.print_link()
print('-'*20)
link.delete_node_byid(2)
link.print_link()
print('-'*20)
link.insert_node(2,100)
link.print_link()
print('-'*20)
link.insert_node(0,100)
link.print_link()
print('-'*20)
print(link.find_node(100))