[LeetCode-237]Delete Node in a Linked List(java)

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值