python 链表

pyhon 链表

#定义节点类
class ListNode(object):
    def __init__(self, data=0, next=None):
        self.data = data
        self.next = next

#将节点链接起来组成链表结构
head = None
for i in range(1,6):
    head = ListNode(i,head) 

#遍历链表
probe = head
while probe != None:
    print(probe.data)
    probe = probe.next

#搜索目标target
probe = head
while probe != None and probe.data != target:
    probe = probe.next
if probe is None:
    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 -= 1
print(probe.data)  # 这里包含了i=0的情况

#插入---在开始处插入
head = ListNode(newItem,head)

#插入---在末尾处插入
newNode = ListNode(newItem)
if not head:
    head = newNode   #原链表为None时,直接指向新节点
else:
    probe = head
    while probe != None:
        probe = probe.next #执行完此处后,probe指向了最后一个节点
    probe.next = newNode   #原链表不为空时,最后一个节点指向新节点


#插入---在第i个位置插入(包含了开始和末尾)
if head is None or i <= 0:
    head = ListNode(newItem,head)   # 原链表为空或i<=0,可以理解为在开始处插入
head = probe
while index > 1  and 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.next is None:
    head = None
else:
    probe = head
    while probe.next.next != None:
        probe = probe.next  # 循环执行完,probe指向了倒数第二个节点
    probe.next = None  # 倒数第二个节点指向None

#删除---在第i个位置删除 
if i <= 0 or head.next is None:
    head = head.next
else:
    probe = head
    while i > 1 and 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      


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值