237. Delete Node in a Linked List
237. Delete Node in a Linked List
题目
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 givennode
.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.
Example 1:
![](https://assets.leetcode.com/uploads/2020/09/01/node1.jpg)
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:
![](https://assets.leetcode.com/uploads/2020/09/01/node2.jpg)
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.
Constraints:
- The number of the nodes in the given list is in the range
[2, 1000]
. -1000 <= Node.val <= 1000
- The value of each node in the list is unique.
- The
node
to be deleted is in the list and is not a tail node.
题目大意
有一个单链表的 head
,我们想删除它其中的一个节点 node
。
给你一个需要删除的节点 node
。你将 无法访问 第一个节点 head
。
链表的所有值都是 唯一的,并且保证给定的节点 node
不是链表中的最后一个节点。
删除给定的节点。注意,删除节点并不是指从内存中删除它。这里的意思是:
- 给定节点的值不应该存在于链表中。
- 链表中的节点数应该减少
1
。 node
前面的所有值顺序相同。node
后面的所有值顺序相同。
自定义测试:
- 对于输入,你应该提供整个链表
head
和要给出的节点node
。node
不应该是链表的最后一个节点,而应该是链表中的一个实际节点。 - 我们将构建链表,并将节点传递给你的函数。
输出将是调用你函数后的整个链表。
解题思路
其实就是把后面的结点都覆盖上来即可,当前结点的值等于下一个结点,Next 指针指向下下个结点。
代码
/**
* @param {ListNode} node
* @return {void} Do not return anything, modify node in-place instead.
*/
var deleteNode = function (node) {
node.val = node.next.val;
node.next = node.next.next;
};
相关题目
- [203. 移除链表元素](./0203.md)
- [2487. 从链表中移除节点](https://leetcode.com/problems/remove-nodes-from-linked-list)