题目
实现一个栈,栈初始为空,支持四种操作:
push x – 向栈顶插入一个数 x;
pop – 从栈顶弹出一个数;
empty – 判断栈是否为空;
query – 查询栈顶元素。
现在要对栈进行 M 个操作,其中的每个操作 3 和操作 4 都要输出相应的结果
输入:
运行的次数
10
每次传入的数据,模式和元素或者下标
push 5
query
push 6
pop
query
pop
empty
push 4
query
empty
输出:
5
5
YES
4
NO
public class 栈_数组模拟 {
//初始化stack和指针index
public static int N = 100010, index = 0;
public static int[] stack = 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();}
}
}
//模拟stack的四种操作,stack的操作应该没什么可讲的吧?
public static void push(int x) {stack[++index] = x;}
public static void pop() {index--;}
public static void empty() {
if (index > 0) {System.out.println("NO");}
else {System.out.println("YES");}
}
public static void query() {System.out.println(stack[index]);}
}
简简单单拿下,打游戏走起~
声明:算法思路来源为y总,详细请见https://www.acwing.com/
本文仅用作学习记录和交流