LeetCode 题解工作台

删除链表中的节点

有一个单链表的 head ,我们想删除它其中的一个节点 node 。 给你一个需要删除的节点 node 。你将 无法访问 第一个节点 head 。 链表的所有值都是 唯一的 ,并且保证给定的节点 node 不是链表中的最后一个节点。 删除给定的节点。注意,删除节点并不是指从内存中删除它。这里的意思是…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们可以将当前节点的值替换为下一个节点的值,然后删除下一个节点。这样就可以达到删除当前节点的目的。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一个单链表的 head,我们想删除它其中的一个节点 node

给你一个需要删除的节点 node 。你将 无法访问 第一个节点  head

链表的所有值都是 唯一的,并且保证给定的节点 node 不是链表中的最后一个节点。

删除给定的节点。注意,删除节点并不是指从内存中删除它。这里的意思是:

  • 给定节点的值不应该存在于链表中。
  • 链表中的节点数应该减少 1。
  • node 前面的所有值顺序相同。
  • node 后面的所有值顺序相同。

自定义测试:

  • 对于输入,你应该提供整个链表 head 和要给出的节点 nodenode 不应该是链表的最后一个节点,而应该是链表中的一个实际节点。
  • 我们将构建链表,并将节点传递给你的函数。
  • 输出将是调用你函数后的整个链表。

 

示例 1:

输入:head = [4,5,1,9], node = 5
输出:[4,1,9]
解释:指定链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9

示例 2:

输入:head = [4,5,1,9], node = 1
输出:[4,5,9]
解释:指定链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9

 

提示:

  • 链表中节点的数目范围是 [2, 1000]
  • -1000 <= Node.val <= 1000
  • 链表中每个节点的值都是 唯一
  • 需要删除的节点 node链表中的节点 ,且 不是末尾节点
lightbulb

解题思路

方法一:节点赋值

我们可以将当前节点的值替换为下一个节点的值,然后删除下一个节点。这样就可以达到删除当前节点的目的。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next
speed

复杂度分析

指标
时间O(1)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate explain why this approach works even without accessing the head of the list?

  • question_mark

    Does the candidate understand the nuances of pointer manipulation and its impact on the linked list?

  • question_mark

    Is the candidate able to optimize the solution for constant time and space complexities?

warning

常见陷阱

外企场景
  • error

    Candidates may mistakenly attempt to traverse the list from the head, which is unnecessary since the problem explicitly denies access to the head node.

  • error

    Not understanding how pointer manipulation works can lead to incorrect handling of the node deletion.

  • error

    Failing to realize that the given node will never be the tail node might cause confusion about edge cases.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the given node is at the beginning of the list?

  • arrow_right_alt

    How would the approach change if you had access to the head of the list?

  • arrow_right_alt

    Can the solution be generalized to remove nodes in a doubly linked list?

help

常见问题

外企场景

删除链表中的节点题解:链表指针操作 | LeetCode #237 中等