Acwing828模拟栈

题目

实现一个栈,栈初始为空,支持四种操作:

  1. push x -- 向栈顶插入一个数 x;
  2. pop -- 从栈顶弹出一个数;
  3. empty -- 判断栈是否为空;
  4. query -- 查询栈顶元素。

现在要对栈进行 M 个操作,其中的每个操作 33 和操作 44 都要输出相应的结果。

输入格式

第一行包含整数 M,表示操作次数。

接下来 M 行,每行包含一个操作命令,操作命令为 push xpopemptyquery 中的一种。

输出格式

对于每个 emptyquery 操作都要输出一个查询结果,每个结果占一行。

其中,empty 操作的查询结果为 YESNOquery 操作的查询结果为一个整数,表示栈顶元素的值。

数据范围

1≤M≤100000 1≤x≤10^9 所有操作保证合法。

输入样例:

perl 复制代码
10
push 5
query
push 6
pop
query
pop
empty
push 4
query
empty

输出样例:

objectivec 复制代码
5
5
YES
4
NO

代码

java 复制代码
import java.util.Scanner;

public class Main {
    static int idx = -1, N = 100010;
    static int[] stk = new int[N];
    static void push(int x) {
        stk[++ idx] = x;
    }
    static void pop() {
        idx --;
    }
    static String empty() {
        return idx == -1 ? "YES" : "NO";
    }
    static int query() {
        return stk[idx];
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        while (m > 0) {
            m --;
            String s= in.next();
            if (s.equals("push")) {
                int x = in.nextInt();
                push(x);
            } else if (s.equals("query")) {
                System.out.println(query());
            } else if (s.equals("pop")) {
                pop();
            } else {
                System.out.println(empty());
            }
        }
    }
}
相关推荐
传奇开心果编程21 分钟前
【Go入门练中学】第2课:条件与循环
后端·学习·golang
wno70438 分钟前
Spring Security基础使用
java·后端·spring
Go_error44 分钟前
那个让我们损失了 47,000 美元 AWS 账单的互斥锁错误
后端
Go_error1 小时前
接口何时冗余:一种用于 Go 测试的精简依赖注入方法
后端
鱼弦1 小时前
长尾场景的挑战:大模型如何处理极其冷门的知识?
后端
孙启超1 小时前
【AI开发之Rust】第 8 课:泛型、trait 与 trait 对象
开发语言·后端·rust
co松柏1 小时前
一文吃透 Pi:10w stars 的极简 Agent harness
后端·架构
joinwell521 小时前
没收到回复,再点一次会启动两个 AI 吗?
人工智能·后端
苏三说技术1 小时前
JDK27正式发布,人麻了!
后端
小蒜学长1 小时前
基于RFID技术的仓储管理系统设计(代码+数据库+LW)
java·数据库·spring boot·后端·rfid技术·仓储管理