1.思路
用一个数组模拟队列,思路很简单,直接看代码就行
2.代码模板
import java.util.*;
class Main{
static int N = 100010;
static int[] q = new int[N];
static int hh = 0; //代表队头指针
static int tt = -1; //代表队尾指针
static void push(int x){
q[++tt] = x;
}
static void pop(){
hh++;
}
static int query(){
return q[hh];
}
static boolean empty(){
if(tt >= hh)
return false;
else
return true;
}
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int m = in.nextInt();
while(m --> 0){
String op = in.next();
switch (op) {
case "push": push(in.nextInt()); break;
case "pop": pop(); break;
case "empty": System.out.println(empty() ? "YES" : "NO"); break;
case "query": System.out.println(query()); break;
}
}
}
}
3.复杂度分析
- 时间复杂度:O(1)
- 空间复杂度:O(n)