LeetCode 237 Delete Node in a LinkedList 题解

题目

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

  Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

思路

  单链表要删除,必须知道要删除结点的前一个结点。但此题困难在于只给了要删除结点的引用,而无法获知该g结点的前一个结点,因此按传统方法无法删除。

  但这题其实非常简单,换种思路,我们把删除该结点改为删除该结点的下一个结点,但在删除之前把下一个结点的值覆盖此结点的值。因此,虽然物理上删除的是下一个结点,但实际上该结点的值已经被删除了,而下一个结点的值仍然保留下来。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
private ListNode first;
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}