1.思路
用一个数组模拟栈,思路很简单,直接看代码就行
2.代码模板
import java.util.*;
public class Main {
static final int N = 100010; //模拟的栈大小
static int[] s = new int[N]; //模拟的栈
static Scanner in = new Scanner(System.in);
static int tt = 0; //指向当前栈顶元素
static void push(int x) {
s[++tt] = x;
}
static void pop() {
tt--;
}
static boolean empty() {
return tt == 0;
}
static int query() {
return s[tt];
}
public static void main(String[] args) {
String op = null;
int m = in.nextInt();
while (m --> 0) {
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)