顺序栈

/*实验2
2.  完成对顺序栈结构的定义,以及对顺序栈的各种基本运算的实现
(每种基本运算用一个函数来实现)。
基本运算包括:
初始化Init_sqstack运算、
判栈空Empty_sqstack运算、
入栈Push_sqstack运算、
出栈Pop_sqstack运算、
取栈顶元素Gettop_sqstack运算。
并且在main函数中分别调用以上各种基本运算的函数来使用,
以证明其功能已实现。此题的源程序保存为 3_a1.cpp。
*/
#include<iostream>
using namespace std;

typedef char datatype; //栈元素类型,假设为整型
const int maxsize=100; //栈容量
typedef struct {
   datatype data[maxsize];
   int top;
} sqstack;			//顺序栈类型

sqstack* Init_sqstack( ) 
{
    sqstack *sq = new sqstack;
    sq->top=-1;
    return sq;
}

int Empty_sqstack(sqstack *sq) 
{
	if(sq->top==-1) 
		return 1;
	else 
		return 0;
}

int Push_sqstack(sqstack *sq,datatype x) 
{
	if(sq->top==maxsize-1)//上溢
    {
		cout<<"栈满,不能入栈!\n";
		return 0;
	} 
	else
    {
		++sq->top;
		sq->data[sq->top]=x; 
		return 1;
	}
}

int Pop_sqstack(sqstack *sq,datatype &x)
{
	if(sq->top==-1)//下溢
    {
		cout<<"栈空,不能出栈!\n"; 
		return 0;
	}
	else
    {
		x = sq->data[sq->top]; 
		sq->top--;
		return 1;
	}
}

int Gettop_sqstack(sqstack *sq,datatype &x) 
{
	if(sq->top==-1)
    {
		cout<<"栈空,无栈顶可取!\n"; 
		return 0;
	}
	else 
    {
		x = sq->data[sq->top];
		return 1;
	}
}

void Display(sqstack *sq)
{
	int i;
	if(Empty_sqstack(sq))
	{
		cout<<"此时栈为空。"<<endl;
	}
	else
	{
		cout<<"栈底到栈顶的元素依次是:";
		for(i=0 ; i<=sq->top ;i++)
			cout<<sq->data[i]<<"  ";
		cout<<endl;
	}
}

int main()
{
	sqstack *S;
	S=Init_sqstack();

	char choice,x;
	int flag = 1;
	while(flag)
	{
		cout<<"------------顺序栈------------------------------"<<endl;
		cout<<"        1. 入栈                                 "<<endl;
		cout<<"        2. 出栈                                 "<<endl;
		cout<<"        3. 取栈顶元素                           "<<endl;
		cout<<"        4. 判断栈是否为空                       "<<endl;
		cout<<"        5. 浏览栈底到栈顶所有元素(测试用)     "<<endl;
		cout<<"        6. 退出                                 "<<endl;
		cout<<"------------------------------------------------"<<endl;
		cout<<"请选择:";

		cin>>choice;
		switch(choice)
		{
		case '1':	cout<<"请输入一个需要入栈的字符"<<endl;
					cin>>x;
					if(Push_sqstack(S,x))
						cout<<"入栈成功"<<endl;
					else
						cout<<"入栈失败!"<<endl;
					break;

		case '2':   if(Pop_sqstack(S,x))
						cout<<"出栈成功,弹出栈的元素是:"<<x<<endl;
					else
						cout<<"出栈失败!"<<endl;
					break;

		case '3':	if(Gettop_sqstack(S,x))
						cout<<"取栈顶元素成功,弹出栈的元素是:"<<x<<endl;
					else
						cout<<"取栈顶元素失败!"<<endl;
					break;

		case '4':   if(Empty_sqstack(S))
						cout<<"此时栈为空。"<<x<<endl;
					else
						cout<<"此时栈不为空。"<<endl;
					break;

		case '5':   Display(S);
					break;

		case '6':   flag=0; 
					break;
		default :   cout<<"输入错误,请重新选择。"<<endl;
		}

	}
	return 0;
}






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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值