编写一个程序实现顺序栈(假设栈中元素类型为char)的各种基本运算

编写一个程序实现顺序栈(假设栈中元素类型为char)的各种基本运算,并在此基础上设计一个主程序完成如下功能:

(1)初始化顺序栈S;

(2)判断顺序栈S是否为空;

(3)依次进栈元素a,b,c,d,e;

(4)判断顺序栈S是否为空;

(5)输出顺序栈长度;

(6)输出从栈顶到栈底的元素;

(7)输出出栈序列;

(8)判断顺序栈S是否为空;

(9)释放顺序栈。

输入

两行数据,第一行是入栈字符数据的个数,第二行是具体入栈的字符数据。

输出

按照程序要求输出。

样例输入

5
a b c d e

样例输出

yes
no
5
e d c b a
e d c b a
yes

代码实现:

#include<iostream>
using namespace std;
typedef char ElemType;
typedef struct{
	ElemType *data;
	int top;
}Sqstack; 
void init(Sqstack &s,int n){
	s.data = new ElemType[n];
	s.top = -1;
}
bool empty(Sqstack s){
	return s.top == -1;
}
void push(Sqstack &s,ElemType e){
	s.data[++s.top] = e;
}
void display(Sqstack s){
	for(int i=s.top;i>=0;i--){
		cout<<s.data[i]<<" ";
	}
	cout<<endl;
}
void pop(Sqstack &s){
	if(empty(s)) return;
	s.top--;
}
ElemType top(Sqstack s){
	return s.data[s.top];
}
int size(Sqstack s){
	return s.top+1;
}
void destroy(Sqstack &s){
	delete []s.data;
}
int main(void){
	Sqstack s;
	int n;
	cin>>n;
	init(s,n);
	if(empty(s)) cout<<"yes"<<endl;
	else cout<<"no"<<endl;
	for(int i=0;i<n;i++){
		ElemType e;
		cin>>e;
		push(s,e);
	}
	if(empty(s)) cout<<"yes"<<endl;
	else cout<<"no"<<endl;
	cout<<size(s)<<endl;
	display(s);
	while(!empty(s)){
		cout<<top(s)<<" ";
		pop(s);
	}
	cout<<endl;
	if(empty(s)) cout<<"yes"<<endl;
	else cout<<"no"<<endl;
	destroy(s);
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

云曦.三清幽者

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

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

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

打赏作者

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

抵扣说明:

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

余额充值