栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

牛客网:AB9 【模板】链表

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

牛客网:AB9 【模板】链表


import sun.net.www.HeaderParser;

import java.security.PrivateKey;
import java.util.Scanner;



public class Solution {
    public static void main(String[] args) {
        MyNode node = new MyNode();
        Scanner scanner = new Scanner(System.in);
        int num = scanner.nextInt();
        scanner.nextLine();

        for (int i= 0; i < num; i++){
            String str = scanner.nextLine();
            String[] split = str.split("\s+");
            if ("insert".equals(split[0])){
                node.insert(Integer.parseInt(split[1]), Integer.parseInt(split[2]));
            } else if ("delete".equals(split[0])){
                node.delete(Integer.parseInt(split[1]));
            }

        }
        node.print();
    }

}


class MyNode{

    private Node root; // 真实的链表

    public MyNode(){};


    public void insert(int x, int y){
        if (root == null){
            root = new Node(y);
            return;
        }

        Node head = new Node(-1, root);
        Node pre = head;
        while (pre.next != null && pre.next.value != x){
            pre = pre.next;
        }

        pre.next = new Node(y, pre.next);
        root = head.next;
    }

    public void delete(int x){
        Node head = new Node(-1, root); // 头节点
        Node pre = head;
        while (pre.next != null && pre.next.value != x){
            pre = pre.next;
        }

        if (head == null){
            return;
        }

        pre.next = pre.next == null ? null : pre.next.next;
        root = head.next;
    }

    public void print(){
        if (root == null){
            System.out.println("NULL");
        } else {
            root.print();
        }
    }

    
    class Node{
        private int value;
        private Node next;

        public Node(){};
        public Node(int value){
            this.value = value;
        }

        public Node(int value, Node next){
            this.value = value;
            this.next = next;
        }

        public void print(){
            System.out.print(this.value + " ");
            if (this.next != null){
                this.next.print();
            }
        }

    }
}

代码如上,可以直接编译哈。

讨论算法的话,可以私聊我哈,一起学习

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936811.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号