删除链表的中间节点

删除链表的中间节点

http://www.nowcoder.com/questionTerminal/0796dbf0eb054716937b0b82e0671c5f

删除链表中的节点,本质都是找到其前一个节点,不知道为啥这么慢>><<

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
    static class Node {
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String[] str = reader.readLine().split(" ");
        int n = Integer.parseInt(str[0]);
        int k = Integer.parseInt(str[1]);
        str = reader.readLine().split(" ");
        reader.close();
        int[] arr = parseArr(str, n);
        Node head = createList(arr);//head为头节点
        head = deleteNode(head, k);
        while (head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    private static Node deleteNode(Node head, int k) {
        if (head == null || head.next == null || k <= 0) return head;
        Node cur = head;
        while( --k > 0){
            if (cur == null) throw new IllegalArgumentException("无效的k");
            cur = cur.next;   
        }
        cur.next = cur.next.next;
        return head.next;
    }

    private static int[] parseArr(String[] str, int n) {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(str[i]);
        }
        return arr;
    }

    private static Node createList(int[] arr) {
        Node head = new Node(-1);
        Node cur = head;
        for (int value : arr) {
            cur.next = new Node(value);
            cur = cur.next;
        }
        return head;
    }
}
全部评论

相关推荐

机械打工仔:第一位颇有孟德之志
点赞 评论 收藏
分享
06-26 18:30
门头沟学院 Java
据说名字越长别人越关注你的昵称我觉得我要被关注了:你问问这里面有多少是正经候选人,而不是乱打招呼的
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务