模拟栈操作

题目描述

给出n种栈操作,包括
push x ,将整数x入栈
pop,弃栈顶,成功则输出pop x,否则输出pop fail
top,取栈顶,成功则输出top = x,否则输出top fail
size,求栈内元素数,输出size = x
empty,询问栈是否为空,为空则输出yes,否则输出no

输入

第一行n,表示n次操作
接下来n行,每行一个操作,格式如上描述

输出

根据操作要求进行输出

样例输入 
6
empty
push 10
empty
size
top 
pop
样例输出
yes
no
size = 1
top = 10
pop 10
解析

主要是对栈操作函数的应用

代码
#include<bits/stdc++.h>
using namespace std;
/*栈STL
1.创建一个栈:stack<int>s;
2.进栈:s.push(x)
3.出栈:s.pop()
4.获取栈顶元素:s.top()
5.求栈内元素个数:s.size()
6.判断栈是否为空:s.empty()  true:空 false:不空	*/
int main(){
	int n;
	cin>>n;
	string m;
	stack<int>s;
	for(int i=1;i<=n;i++){
		cin>>m;
		if(m=="push"){
			int x;
			cin>>x;
			s.push(x);
		}
		else if(m=="pop"){
			if(s.empty()) cout<<"pop fail"<<endl;
			else{
				cout<<"pop "<<s.top()<<endl;
				s.pop();
			}
		}
		else if(m=="top"){
			if(s.empty()) cout<<"top fail"<<endl;
			else cout<<"top = "<<s.top()<<endl;
		}
		else if(m=="size"){
			cout<<"size = "<<s.size()<<endl;
		}
		else if(m=="empty"){
			if(s.empty()) cout<<"yes"<<endl;
			else cout<<"no"<<endl;	
		}
	}

	return 0;
}

点个赞谢谢

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值