java 蓝桥杯 队列操作

题目描述
根据输入的操作命令,操作队列:1 入队、2出队并输出、3 计算队中元素个数并输出。1≤N≤50。

输入描述
第一行一个数字 N。 接下来 N 行,每行第一个数字为操作命令:1入队、2 出队并输出、3 计算队中元素个数并输出。

输出描述
若干行每行显示一个 2 或 3 命令的输出结果。注意:2.出队命令可能会出现空队出队(下溢),请输出“no”,并退出。
输入输出样例
示例
输入

7
1 19
1 56
2
3
2
3
2
copy
输出

19
1
56
0
no
copy
运行限制
最大运行时间:1s
最大运行内存: 128M

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Queue<Integer> q = new Queue<>();
        int num = 0;
        //存储输入的元素值
        ArrayList<Integer> p = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int x = in.nextInt();
            if(x == 1) n++;
            p.add(x);
        }
        //执行输入的命令
        for (int i = 0; i < n; i++) {
            num = p.get(i);
            if(num == 1){
                int y = p.get(i+1);
                q.enqueue(y);
                i = i+1;
            }
            if(num == 2){
                if(q.isEmpty()){
                    System.out.println("no");
                    break;
                }
                System.out.println(q.dequeue());

            }
            if(num == 3){
                System.out.println(q.size());
            }
        }
    }
}
//创建队列类
class Queue<T>{
    private Node head;
    private Node last;
    private int N;

    private class Node{
        public T item;
        public Node next;

        public Node(T item,Node next){
            this.item = item;
            this.next = next;
        }
    }

    public Queue(){
        this.head = new Node(null,null);
        this.last = null;
        this.N = 0;
    }

    public  boolean isEmpty(){
        return N==0;
    }

    public int size(){
        return N;
    }
    //插入元素
    public void enqueue(T t){
        if(last == null){
            last = new Node(t,null);
            head.next = last;
        }else{
            Node oldlast = last;
            last = new Node(t,null);
            oldlast.next = last;
        }
        N++;
    }
    //删除元素
    public T dequeue(){
        if(isEmpty()){
            System.out.println("no");
        }
        Node oldfirst = head.next;
        head.next =oldfirst.next;
        N--;
        if(isEmpty()){
            last =null;
        }
        return oldfirst.item;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值