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.
题意:
写一个函数实现,只给出要删除的节点,但可以删除单链表中除了尾节点之外的任意节点。
分析:
刚开始一直思维一直禁锢在以前固有的模式,即需要前一个节点,才能删除节点,但这里没有给我们链表的起点,只给出了要删除的节点,这和我们通常遇到的情况不一样。通常情况下,我们需要找到要删除节点前面的节点,然后将前面的节点指向要删除节点后面的节点即可。而这里,可以直接用节点node后面的节点node.next的值val覆盖此节点的值,再删除node后面的节点即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
if(node == null)
return;
//用节点node后面的节点node.next的值val覆盖此节点的值
node.val=node.next.val;
//将节点node指向node下下一个节点,即删除node后面的节点
node.next=node.next.next;
}
}