思想
队列
思路
完整代码
import java.util.*;
public class Main{
static int N = 100010;
static int m;//接收用户操作的次数
static String c;//接收用户进行的操作
static int x;//接收用户插入的数字
static int[] q = new int[N];
static int hh;//hh表示在队头插入元素, 头指针
static int tt;//tt表示在队尾插入元素, 尾指针
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
//hh, tt初始化
tt = -1;
hh = 0;
while(m-- != 0){
c = sc.next();
if(c.equals("push")){
x = sc.nextInt();
//队列要在尾部插入数字
q[++tt] = x;
}else if(c.equals("pop")){
//队列弹出一个数要从队头弹出
//也就是第一个插入的数被弹出
//tt初始化为-1, 插入的数字在0索引处, hh初始化为0, hh++后, hh的索引停留在1
//此时输出q[hh], 队列头部变成了q[1], 可以说q[0]虽在,但是此程序中q[0]已经不复存在
hh++;
}else if(c.equals("empty")){
//判断队列是否为空
if(hh <= tt)
System.out.println("NO");
else
System.out.println("YES");
}else{
//输出头部元素
System.out.println(q[hh]);
//输出尾部元素,也就是新插入的元素q[tt]
}
}
}
}