AcWing - 模拟栈(栈&模拟)
发布日期:2021-07-01 00:21:57 浏览次数:3 分类:技术文章

本文共 1202 字,大约阅读时间需要 4 分钟。

题目链接:

时/空限制:1s / 64MB

题目描述

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

(1) “push x” – 向栈顶插入一个数x;

(2) “pop” – 从栈顶弹出一个数;

(3) “empty” – 判断栈是否为空;

(4) “query” – 查询栈顶元素。

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

输入格式

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

接下来M行,每行包含一个操作命令,操作命令为”push x”,”pop”,”empty”,”query”中的一种。

输出格式

对于每个”empty”和”query”操作都要输出一个查询结果,每个结果占一行。

其中,”empty”操作的查询结果为“YES”或“NO”,”query”操作的查询结果为一个整数,表示栈顶元素的值。

数据范围

1≤M≤100000,

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

输入样例

10

push 5
query
push 6
pop
query
pop
empty
push 4
query
empty

输出样例

5

5
YES
4
NO

解题思路

题意:模拟一个栈,共有四种操作。

思路:直接模拟,写的是数组型的,不过操作和指针的类似。

Accepted Code:

/*  * @Author: lzyws739307453  * @Language: C++  */#include 
using namespace std;const int MAXN = 100005;int Stack[MAXN], top = 0;void push(int x) { Stack[++top] = x;}void pop() { top--;}bool empty() { return !top;}int Query() { return Stack[top];}int main() { char op[7]; int n, k, x; scanf("%d", &n); while (n--) { scanf("%s", op); if (!strcmp(op, "push")) { scanf("%d", &x); push(x); } else if (!strcmp(op, "pop")) pop(); else if (!strcmp(op, "empty")) printf(empty() ? "YES\n" : "NO\n"); else printf("%d\n", Query()); } return 0;}

转载地址:https://lzyws739307453.blog.csdn.net/article/details/99959685 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:AcWing - 模拟队列(队列&模拟)
下一篇:AcWing - 双链表(模拟)

发表评论

最新留言

很好
[***.229.124.182]2024年04月26日 15时34分22秒