• 【Leetcode】剑指Offer 18:删除链表的节点


    给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
    返回删除后的链表的头节点。
    注意:此题对比原题有改动
    示例 1:
    输入: head = [4,5,1,9], val = 5
    输出: [4,1,9]
    解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
    示例 2:
    输入: head = [4,5,1,9], val = 1
    输出: [4,5,9]
    解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
    说明:
    题目保证链表中节点的值互不相同
    若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    AC代码

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        def deleteNode(self, head: ListNode, val: int) -> ListNode:
            parent = head
            if parent.val == val:
                return parent.next
            while parent != None:
                if parent.next.val == val:
                    parent.next = parent.next.next
                    return head
                else:
                    parent = parent.next
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    官方代码

    class Solution:
        def deleteNode(self, head: ListNode, val: int) -> ListNode:
            if head.val == val: return head.next
            pre, cur = head, head.next
            while cur and cur.val != val:
                pre, cur = cur, cur.next
            if cur: pre.next = cur.next
            return head
    
    作者:jyd
    链接:https://leetcode.cn/problems/shan-chu-lian-biao-de-jie-dian-lcof/solution/mian-shi-ti-18-shan-chu-lian-biao-de-jie-dian-sh-2/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    这个解法说是双指针,但本质上和笔者上面的那个代码是一致的,简单题也没啥能说的。

  • 相关阅读:
    强化学习输入数据归一化(标准化)
    SpringBoot 整合 RabbitMQ 实现消息可靠传输
    Linux CentOS 8(用户管理)
    2023-09-22力扣每日一题
    Apache OFBiz 路径遍历导致RCE漏洞复现(CVE-2024-36104)
    ElasticSearch 狂神说
    安卓手机部署大模型实战
    接口测试经典面试题:Session、cookie、token有什么区别?
    【Java愚公】idea打开svn项目看不到Subversion
    浏览器---chrome 高级调试技巧汇总(后期继续添加)
  • 原文地址:https://blog.csdn.net/qq_44459787/article/details/126766694