顺序栈的基本操作实现

#include<stdlib.h>
#include<iostream>
using namespace std;
#define StackSize 100					//顺序栈的初始分配空间
typedef struct
{
	char data[StackSize];			//保存栈中元素
	int top;							//栈指针
}SqStack;
void InitStack(SqStack *st)				//*st为引用型参数
{
	st->top=-1;
}
int push(SqStack *st,char x)		//进栈运算
{
	if(st->top==StackSize-1)			//栈满
		return 0;
	else
	{
		st->top++;						//栈不满
		st->data
			[st->top]=x;
		return 1;
	}
}
int pop(SqStack *st,char  *x)		//出栈运算,*st,*x都为引用型参数
{
	if(st->top=-1)						//栈空
		return 0;
	else
	{
		*x=st->data[st->top];			//栈不空
		st->top--;
		return 1;
	}
}
int gettop(SqStack *st,char *x)		//取栈顶元素,x为引用型参数
{
	if(st->top==-1)						//栈空
		return 0;
	else
	{
		*x=st->data[st->top];
		return 1;
	}
}
int getall(SqStack *st,char *x)
{
	if(st->top==-1)
		return 0;
	else
	{
		while(st->top!=-1)
		{
		*x=st->data[st->top];
		cout<<*x;
		st->top--;
		}
	}
}
int StackEmpty(SqStack *st)				//判断栈是否为空
{
	if(st->top==-1)
		return 1;
	else
		return 0;
}
void main()
{
	SqStack st;
	char e;
	InitStack(&st);
	cout<<"栈";
	if(StackEmpty(&st)==1)
		cout<<"空"<<endl;
	else
		cout<<"不空"<<endl;
	cout<<"a 进栈"<<endl;push(&st,'a');
	cout<<"b 进栈"<<endl;push(&st,'b');
	cout<<"c 进栈"<<endl;push(&st,'c');
	cout<<"d 进栈"<<endl;push(&st,'d');
	cout<<"e 进栈"<<endl;push(&st,'e');
	cout<<"栈";
	if(StackEmpty(&st)==1)
		cout<<"空"<<endl;
	else
		cout<<"不空"<<endl;
	gettop(&st,&e);
	cout<<"栈顶元素"<<endl;
	cout<<"出栈次序";
	getall(&st,&e);
	while(!StackEmpty(&st))
	{
		pop(&st,&e);
		cout<<e;
	}
	cout<<"\n";
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值