leetcode 237. Delete Node in a Linked List(链表中删除节点)

本文介绍了一种在不获取链表头节点的情况下删除指定中间节点的方法。通过将待删节点的值替换为下一个节点的值并调整指针,实现节点的有效删除,保持了链表的原有顺序。

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

There is a singly-linked list head and we want to delete a node node in it.

You are given the node to be deleted node. You will not be given access to the first node of head.

All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.

Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:

The value of the given node should not exist in the linked list.
The number of nodes in the linked list should decrease by one.
All the values before node should be in the same order.
All the values after node should be in the same order.
Custom testing:

For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.
We will build the linked list and pass the node to your function.
The output will be the entire list after calling your function.
在这里插入图片描述
看题目有点茫然,不知道让干嘛。
然后分析一下是这样的:
测试平台有一个单向链表(但是不会给你),它会调用deleteNode(node)函数(你负责实现这个函数),
调用完之后node这个节点会被删掉。

所以你知道的信息只有node这个节点,链表本身是什么你并不知道。
node不是tail节点。

思路:

我们负责实现的是deleteNode这个函数,传来的信息只有要删除的节点node.
同时还有node.next, node.val这些信息。

由于没有前一个节点,并不能删掉node本身,但可以删掉下一节点。
题目中也说了,删除node并不意味着要把node移出内存,只是要求它的值不在链表中出现,
链表保持原顺序即可,
而且node不是tail节点,这说明我们可以删除下一节点,然后把node的值变为下一节点的值即可。

public void deleteNode(ListNode node) {
    ListNode nextNode = node.next;
    int nextVal = nextNode.val;
    node.next = nextNode.next;
    nextNode.next = null;
    node.val = nextVal;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值