您的位置:首页 > 其它

栈的顺序存储及其基本操作

2013-08-14 11:13 357 查看
#include <stdio.h>
#include <stdlib.h>
#define M 10

typedef struct   //定义一个顺序栈
{
char data[M];
int top;
}SqStack;

void InitStack(SqStack &st)//创建一个栈
{
st.top=-1;
}

int PushStack(SqStack &st, char x)//进栈操作
{
if(st.top==M-1)
return 0;
else
{
st.top++;
st.data[st.top]=x;
return 1;
}
}

int PopStack(SqStack &st,char &x)  //出栈操作
{
if(st.top==-1)
return 0;
else
{
x=st.data[st.top];
st.top--;
return 1;
}
}

int GetTop(SqStack st,char &x)   //取栈顶元素
{
if(st.top==-1)
return 0;
else
{
x=st.data[st.top];
return 1;
}
}

int StackEmpty(SqStack st)  //判断栈空
{
if(st.top==-1)
return 1;
else
return 0;
}

int main()
{
SqStack st;
char e;
InitStack(st);
printf("栈%s\n",(StackEmpty(st)==1?"空":"不空"));
printf("a进栈\n");PushStack(st,'a');
printf("b进栈\n");PushStack(st,'b');
printf("c进栈\n");PushStack(st,'c');
printf("d进栈\n");PushStack(st,'d');
printf("栈%s",(StackEmpty(st)==1?"空":"不空"));
GetTop(st,e);
printf("栈顶元素:%c\n",e);
printf("出栈次序:");
while(!StackEmpty(st))
{
PopStack(st,e);
printf("%c ",e);
}
printf("\n");
return 0;
}
输入元素后输出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: