原题链接: 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.
注意事项:
- 链表中至少有2个元素
- 所有链表节点的值,都是互不相同的
- 给出的节点,不会是链表的尾节点,并且一定是链表中一个有效的节点。
- 函数不需要返回任何值
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/