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

题目描述
给定一个链表,实现删除链表第 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;
    }
}
   
发布了189 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44406146/article/details/105285547