[牛客网刷题 Day3] JZ18 删除链表的节点

本文探讨了如何使用双指针技巧高效地在Python链表中删除值为`val`的节点。通过实例代码,展示了两种方法:一种是利用before和after节点进行替换,另一种是仅用单个游标遍历。这两种方法简化了操作,避免了丢失节点的问题。
摘要由CSDN通过智能技术生成

题目

在这里插入图片描述

思考:

记录目标节点前的位置before,以及目标节点以后的位置after,再用before.next=after,不过还是遇到了老问题!before走着走着,就丢掉了前面的点了!需要一个dummy=before,指向同一个地址,再让before指向after,就好啦。
其实不要after节点也可以呢,before指向cur.next也是一样的道理呢。

class Solution:
    def deleteNode(self , head: ListNode, val: int) -> ListNode:
        if head is None:
            return None
        if head.val == val:
            return head.next
        curr = head
        dummy = before = head
        while curr:
            if curr.val == val:
                curr = curr.next
                break
            else:
                before = curr
                curr = curr.next
        before.next = curr
        return dummy

看了一下参考答案,只用到了两个指针,head一直往后走,遇到目标值就head.next = head.next.next

class Solution:
    def deleteNode(self , head: ListNode, val: int) -> ListNode:
        # write code here
        cur=head
        while head and head.next:
            if head.next.val==val:
                if head.next.next==None:
                    head.next=None
                    return cur
                else:
                    head.next=head.next.next
            if head.val==val:
                return head.next
            head=head.next
        return cur
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值