[LeetCode] 237. Delete Node in a Linked List

本文介绍了一种特殊的链表节点删除方法,仅通过已知待删除节点来完成删除操作,而无需链表头节点。通过将待删节点值替换为后继节点值并跳过后继节点的方式实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接: https://leetcode.com/problems/delete-node-in-a-linked-list/

1. 题目介绍

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list – head = [4,5,1,9], which looks like following:

写一个函数,删除单向链表中的一个节点(保证该节点不会是链表的最后一个节点)。
这道题的特别之处在于,只会给出被要求删除的那个节点。
在这里插入图片描述
Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, 
the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, 
the linked list should become 4 -> 5 -> 9 after calling your function.

Note:
The linked list will have at least two elements.
All of the nodes’ values will be unique.
The given node will not be the tail and it will always be a valid node of the linked list.
Do not return anything from your function.

注意事项:

  1. 链表中至少有2个元素
  2. 所有链表节点的值,都是互不相同的
  3. 给出的节点,不会是链表的尾节点,并且一定是链表中一个有效的节点。
  4. 函数不需要返回任何值

2. 解题思路

不得不说,这道题真的是画风清奇。正常从链表中删除一个元素,至少要给出链表的头节点吧。但是这道题只给出了要删除的节点。于是一开始真的无从下手。
后来参考了LeetCode上面的题解,才知道这个题有一个巧妙的方法解决。

如果要删除某节点,一般是让这个节点前面的节点指向这个节点后面的节点,绕开自己。比如想要删除3,就让2绕开3,指向4
在这里插入图片描述

但是在本题中,我们只知道要删除的节点的 val 值和下一个节点是谁,无法得出上一个节点的信息。也就是说,我们只知道3, 不知道3前面的是谁,无法改动3前面的元素。

所以我们只好采取这样的办法:用后一个节点的 val 覆盖要删除的节点的 val 。然后绕过后一个节点,直接指向后一个节点的后一个节点。这么说有点绕,我们直接看例子:

要删除 3 节点。
把 3 节点的 val 改为 4
在这里插入图片描述
然后让这个节点直接指向 5
在这里插入图片描述
这样就相当于删除了3节点了。
在这里插入图片描述

实现代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

3. 参考资料

https://leetcode.com/problems/delete-node-in-a-linked-list/solution/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值