237. 删除链表中的节点
题目描述
请编写一个函数,用于 删除单链表中某个特定节点 。在设计函数时需要注意,你无法访问链表的头节点 head ,只能直接访问 要被删除的节点 。
题目数据保证需要删除的节点 不是末尾节点 。
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.
It is guaranteed that the node to be deleted is not a tail node in the list.
// 🌰 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.
// 🌰 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.
提示:
链表中节点的数目范围是 [2, 1000] -1000 <= Node.val <= 1000 链表中每个节点的值都是唯一的 需要删除的节点 node 是 链表中的一个有效节点 ,且 不是末尾节点
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
解题方法
替换节点
思路 拿不到删除节点的前一节点,拿不到前一节点的next,无法和后一节点建立联系,所以可以替换要删除的节点为后一节点
步骤 替换要删除的节点值为后一节点值
复杂度分析
- 时间复杂度:O(1)
- 空间复杂度:O(1)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @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
};