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());
            }
        }
    }
}
相关推荐
一 乐1 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
码事漫谈2 小时前
Protocol Buffers 编码原理深度解析
后端
码事漫谈2 小时前
gRPC源码剖析:高性能RPC的实现原理与工程实践
后端
踏浪无痕4 小时前
AI 时代架构师如何有效成长?
人工智能·后端·架构
程序员小假4 小时前
我们来说一下无锁队列 Disruptor 的原理
java·后端
武子康5 小时前
大数据-209 深度理解逻辑回归(Logistic Regression)与梯度下降优化算法
大数据·后端·机器学习
maozexijr5 小时前
Rabbit MQ中@Exchange(durable = “true“) 和 @Queue(durable = “true“) 有什么区别
开发语言·后端·ruby
源码获取_wx:Fegn08955 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
独断万古他化6 小时前
【Spring 核心: IoC&DI】从原理到注解使用、注入方式全攻略
java·后端·spring·java-ee
毕设源码_郑学姐6 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计