程序员代码面试指南刷题--第二章.一种怪异的节点删除方式

题目描述

链表节点值类型为 int 类型,给定一个链表中的节点 node,但不给定整个链表的头节点。如何在链表中删除 node ? 请实现这个函数。

输入描述:

给出一个单链表的节点。

输出描述:

不需要返回值。

示例1
输入
5 
1 2 3 4 5
3  //牛客上并不是节点的值而是第几个节点
输出
1 2 4 5

备注:

保证要删除的这个节点不是链表的尾节点。

import java.io.*;
public class Main{
    public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static ListNode creat() throws IOException{
        int len = Integer.parseInt(br.readLine());
        String[] ss = br.readLine().trim().split(" ");
        ListNode head = new ListNode(0);
        ListNode r = head;
        for(int i=0;i<len;i++){
            int val = Integer.parseInt(ss[i]);
            ListNode node = new ListNode(val);
            r.next = node;
            r = node;
        }
        return head.next;
    }
    public static void delete(ListNode node){
        if(node==null) return ;
        if(node.next==null) throw new RuntimeException("last node,I dont have method to delete");
        node.val = node.next.val;
        node.next = node.next.next;
    }
    public static void main(String[] args) throws Exception{
        ListNode head = creat();
        int val = Integer.parseInt(br.readLine());
        ListNode tmp = head;
        while((--val)>0){
            tmp = tmp.next;
        }
        delete(tmp);
        StringBuilder sb = new StringBuilder();
        while(head!=null){
            sb.append(head.val).append(" ");
            head = head.next;
        }
        System.out.print(sb.toString());
    }
}
class ListNode{
    int val;
    ListNode next;
    public ListNode(int val){
        this.val = val;
        this.next = next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值