STL之stack

描述

使用STL中的stack,完成入栈、出栈、栈清空等基本操作。

部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码。

 

int main()
{
    stack<int> st;
    int n;
    cin>>n;
    while(n--)
    {
        Op(st);
    }
    while(!st.empty())
    {
        cout<<st.top()<<endl;
        st.pop();
    }
    return 0;
}

输入

输入数据第一行为整数n,接下来有n个命令,其中命令格式:

(1)压栈:push x

(2)出栈:pop

(3)清空:clear

如果部分操作无效,该操作不执行。

输出

执行一系列操作后,输出从栈顶到栈底的所有元素值,每行一个。

样例输入

 5
push 1
push 2
pop
push 3
push 4

样例输出

4
3
1

#include <iostream>
#include <string>
#include <stack>
using namespace std;
void Op(stack<int> &st)
{
    string ss;
    cin>>ss;
    if(ss=="push")
    {
        int n;
        cin>>n;
        st.push(n);
    }
    else if(ss=="pop")
    {
        if(!st.empty())
        {
            st.pop();
        }
    }
    else if(ss=="clear")
    {
        while(!st.empty())
        {
            st.pop();
        }
    }
    else
    {
        if(!st.empty())
        {
            cout<<st.top()<<endl;
        }
    }
}
int main()
{
    stack<int> st;
    int n;
    cin>>n;
    while(n--)
    {
        Op(st);
    }
    while(!st.empty())
    {
        cout<<st.top()<<endl;
        st.pop();
    }
    return 0;
}

 

 

 

转载于:https://www.cnblogs.com/baobao2201128470/p/8722148.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值