题目描述
根据输入的操作命令,操作队列: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;
}
}