假装从零开始学数据结构(Day 4)
其实我有一点点基础,但是感觉基础十分的不扎实,现在我是大一时间还多,所以我打算从零开始学一遍
栈 , 先进后出的一种数据结构,本身难度没有什么,但常常会遇到单调栈相关的题目,就有一定的难度了,我们要先打好基础。
我们用栈模拟几种基本的操作:
实现一个栈,栈初始为空,支持四种操作:
push x
– 向栈顶插入一个数 x;pop
– 从栈顶弹出一个数;empty
– 判断栈是否为空;query
– 查询栈顶元素
#include <iostream>
using namespace std;
int stack[100001], idx = 0;
void push(int a)
{
stack[++idx] = a;
}
void pop()
{
idx--;
}
int empty()
{
if(!idx)
return 0;
else
return 1;
}
int query()
{
return stack[idx];
}
int main()
{
int m;
cin >> m;
string s;
int a;
while(m--)
{
cin >> s;
if(s == "push")
{
cin >> a;
push(a);
}
else if(s == "pop")
{
pop();
} else if(s == "empty")
{
if(empty())
{