牛客网:AB9 【模板】链表

博客提及代码可直接编译,还邀请大家私聊讨论算法,共同学习,涉及Java链表数据结构相关内容。


import sun.net.www.HeaderParser;

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

/**
 * @author xienl
 * @description 链表
 * @date 2022/5/30
 */

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();
            }
        }

    }
}

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值