#P2581. 数组模拟栈

数组模拟栈

Description

#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 top()
{
    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"&&empty()==false)
       {
           pop();
       } else if(s == "empty")
       {
           if(empty())
           {
               cout << "NO" << endl;
           }
           else
               cout << "YES" << endl;
       }
       else if(s == "top"&&empty()==false)
       {
           cout << top() << endl;
       }
   }
    return 0;
}

Source

数据结构 栈 知识点