#定义节点类classListNode(object):def__init__(self, data=0,next=None):
self.data = data
self.next=next#将节点链接起来组成链表结构
head =Nonefor i inrange(1,6):
head = ListNode(i,head)#遍历链表
probe = head
while probe !=None:print(probe.data)
probe = probe.next#搜索目标target
probe = head
while probe !=Noneand probe.data != target:
probe = probe.nextif probe isNone:print("target not in the link")else:print(probe.data)#搜索目标第i个节点:假设链表的节点数为n, 0 <= i <= n-1
probe = head
while i >0:
probe = probe.next
i -=1print(probe.data)# 这里包含了i=0的情况#插入---在开始处插入
head = ListNode(newItem,head)#插入---在末尾处插入
newNode = ListNode(newItem)ifnot head:
head = newNode #原链表为None时,直接指向新节点else:
probe = head
while probe !=None:
probe = probe.next#执行完此处后,probe指向了最后一个节点
probe.next= newNode #原链表不为空时,最后一个节点指向新节点#插入---在第i个位置插入(包含了开始和末尾)if head isNoneor i <=0:
head = ListNode(newItem,head)# 原链表为空或i<=0,可以理解为在开始处插入
head = probe
while index >1and probe.next!=None:
probe = probe.next#循环执行完成,probe指向i-1或最后一个节点
i -=1
probe.next= ListNode(newItem,probe.next)#此处分两段来理解: 1、新节点指向了i或空,2、i-1节点指向了新节点#删除(假设至少有一个节点)#删除---在开始处删除
head = head.next#删除---在末尾删除 if head.nextisNone:
head =Noneelse:
probe = head
while probe.next.next!=None:
probe = probe.next# 循环执行完,probe指向了倒数第二个节点
probe.next=None# 倒数第二个节点指向None#删除---在第i个位置删除 if i <=0or head.nextisNone:
head = head.nextelse:
probe = head
while i >1and probe.next.next!=None:
probe = probe.next#循环执行完,probe指向了i-1或倒数第二个节点
i -=1
probe.next= probe.next.next#前面默认都是从0开始,经常会遇到从1开始,那么添加哑节点吧
dummy = ListNode(0,head)#结果返回 dummy.next