题目
用数组实现一个栈,栈初始为空,支持四种操作:
1,push:向栈顶插入一个数
2,pop:从栈顶弹出一个数
3,empty:判空
4,query:查询栈顶元素
输入格式
第一行包含整数m,表示操作次数;
接下来 m 行,每行包含一个操作命令;
输入样例
10
push 5
query
push 6
pop
query
pop
empty
push 4
query
empty
输出样例
5
5
YES
4
NO
代码
import java.io.*;
public class Main{
static final int N = 100010;
static int m;
static int[] stk = new int[N];
static int top = -1;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
m = Integer.parseInt(br.readLine());
while(m-- > 0){
String[] s = br.readLine().split(" ");
if(s[0].equals("push")){
push(Integer.parseInt(s[1]));
}
else if(s[0].equals("pop")){
pop();
}
else if(s[0].equals("empty")){
System.out.println(empty());
}
else if(s[0].equals("query")){
System.out.println(query());
}
}
}
public static void push(int x){
stk[++top] = x;
}
public static void pop(){
top--;
}
public static String empty(){
if(top < 0){
return "YES";
}
else
return "NO";
}
public static int query(){
return stk[top];
}
}