题目
实现一个队列,队列初始为空,支持四种操作:
push x – 向队尾插入一个数 x;
pop – 从队头弹出一个数;
empty – 判断队列是否为空;
query – 查询队头元素。
现在要对队列进行 M 个操作,其中的每个操作 3 和操作 4 都要输出相应的结果。
输入
运行的次数
10
每次传入的数据,模式和元素或者下标
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
输出
NO
6
YES
4
public class 队列_数组模拟 {
//初始化,head和end指针设置为0,创建queue数组
public static int N = 100010, head = 0, end = 0;
public static int[] q = new int[N];
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int times = Integer.parseInt(in.nextLine());
while (times-- > 0) {
String[] data_arr = in.nextLine().split(" ");
String model = data_arr[0];
if (model.equals("push")) {push(Integer.parseInt(data_arr[1]));}
else if (model.equals("pop")) {pop();}
else if (model.equals("empty")) {empty();}
else if (model.equals("query")) {query();}
}
}
//模拟队列的头出尾进
public static void push(int x) {q[end++] = x;}
public static void pop() {head ++;}
public static void empty() {
if (end - head > 0) {System.out.println("NO");}
else {System.out.println("YES");}
}
public static void query() {System.out.println(q[head]);}
}
声明:算法思路来源为y总,详细请见https://www.acwing.com/
本文仅用作学习记录和交流