您的位置:首页 > 其它

顺序栈的基本操作实现

2012-03-23 10:37 381 查看
#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";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: