0
点赞
收藏
分享

微信扫一扫

栈 计蒜客 - A1047

流沙雨帘 2022-04-04 阅读 72
c++

栈 计蒜客 - A1047

问题描述

这是一个简单的栈问题,你将会有4个操作:
push x 将 x 入栈,
pop 将栈顶元素移除,
sum 是输出此时栈里的元素的个数,
out 是将栈的元素全部输出。

Input:
本题多组测试数据,每组第一行输入一个整数 n (n<100),
代表接下来的操作数。接下来的 n 行输入操作方式。

Output:按题意输出,并换行。

样例输入

7
push 12
push 142
push 456
sum
pop
sum
out

样例输出

3
2
142
12
  • 参考程序
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
const int N=1e5+10;
int sta[N], head=0;

void push(int x) {//入栈
    sta[++head] = x;//[1,N]
}
void pop() {//出栈
    --head;
}
int top() {//栈顶
    return sta[head];
}
bool empty() {//栈空 
    return head==0;
}
int size() {
    return head;
}
void out() {
    for(int i=head; i>=1; i--) {
        cout<<sta[i]<<endl;
    }
}
void init() {
    //memset(sta,0,sizeof(sta));
    head=0;
}
int main() {
    //freopen("data.in","r",stdin);
    int n;
    while(cin>>n) {
    	init(); 
        for(int i=1; i<=n; i++) {
            string op; int x; cin>>op;
            if(op=="push") {
                cin>>x; push(x);
            } else if(op=="sum") {
                cout<<size()<<endl;
            } else if(op=="pop") {
                pop();
            } else if(op=="out") {
                out();
            }
        }
    }
    return 0;
}
举报

相关推荐

0 条评论