程序员代码面试指南刷题--第二章.删除链表的中间节点

题目描述
给定一个链表,实现删除链表第 K 个节点的函数。
输入描述:

n 表示链表的长度。

m 表示删除链表第几个节点。

val 表示链表节点的值。

输出描述:

在给定的函数中返回链表的头指针。

示例1
输入

5 3
1 2 3 4 5

输出

1 2 4 5

解法一:正常写就行

import java.io.*;
public class Main{
    public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static ListNode creat(int len,String[] ss){
        ListNode head = new ListNode(0);
        ListNode r = head;
        for(int i=0;i<len;i++){
            ListNode node = new ListNode(Integer.parseInt(ss[i]));
            r.next = node;
            r = node;
        }
        return head.next;
    }
    public static ListNode del(ListNode head,int index){
        if(head==null) return head;
        ListNode r = new ListNode(0);
        r.next = head;
        ListNode tmp = r;
        while(tmp.next!=null){
            index--;
            if(index==0){
                tmp.next = tmp.next.next;
                break;
            }
            tmp = tmp.next;
        }
        return r.next;
    }
    public static void main(String[] args) throws IOException{
        String[] s1 = br.readLine().trim().split(" ");
        int len = Integer.parseInt(s1[0]);
        int index = Integer.parseInt(s1[1]);
        String[] ss = br.readLine().trim().split(" ");
        ListNode head = creat(len,ss);
        head = del(head,index);
        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、付费专栏及课程。

余额充值