栈操作<模拟栈>(入栈,出栈,肖战,查询栈顶元素,判空)

一、问题:acwing828 模拟栈

在这里插入图片描述在这里插入图片描述

二、思路:

1.本文用栈操作来解决,栈的入栈,出栈,判空,查询栈顶元素等操作是我们需要牢牢记住的
2.栈的操作要点:
后进先出(想象成罐子,后放的东西能先拿出来)
只能在栈顶操作(入栈,出栈,查询栈顶元素)

三、解决问题:

1.STL

#include<iostream>
#include<stack>
using namespace std;
const int N = 100010;
stack<int> st;
int main()
{
    int n;
    cin>>n;
    while(n -- )
    {
        string op;
        cin>>op;
        int x;
        if(op=="push")
        {
            cin>>x;
            st.push(x);
            
        }
        else if(op=="pop")
        {
            st.pop();
        }
        else if(op=="query")
        {
                cout<<st.top()<<endl;
        }
        else if(op=="empty")
        {
            if(st.empty())cout<<"YES";
            else cout << "NO";
            cout<<endl;
        }
    }
}

2.模拟栈

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int stack[N];
int top=-1;
void push()
{
    int x;
    cin>>x;
    stack[++top]=x;
}
void pop()
{
    top--;
}
void query()
{
    if(top==-1)cout<<"你干嘛";
    else cout<< stack[top]<<endl;
}
void empty()
{
    if(top==-1)cout<<"YES";
    else cout<<"NO";
    cout<<endl;
}
void pick(string op)
{
    if(op=="push")push();
    else if(op=="pop")pop();
    else if(op=="query")query();
    else if(op=="empty")empty();
}
int main()
{
    int n;
    cin>>n;
    while (n -- )
    {
        string op;
        cin>>op;
        pick(op);
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

热血少年鸡小龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值