顺序栈的基本运算
栈的定义
#include <stdio.h>
typedef char ElemType;
#define StackSize 100
typedef struct
{
ElemType data[StackSize];
int top;
} SqStack;
初始化栈
void InitStack(SqStack &st)
{
st.top=-1;
}
进栈运算
int Push(SqStack &st,ElemType x)
{
if (st.top==StackSize-1)
return 0;
else
{
st.top++;
st.data[st.top]=x;
return 1;
}
}
出栈运算
int Pop(SqStack &st,ElemType &x)
{
if (st.top==-1)
return 0;
else
{
x=st.data[st.top];
st.top--;
return 1;
}
}
取栈顶元素
int GetTop(SqStack st,ElemType &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;
}
main
void main()
{
SqStack st;
ElemType e;
InitStack(st);
printf("栈%s\n",(StackEmpty(st)==1?"空":"不空"));
printf("a进栈\n");Push(st,'a');
printf("b进栈\n");Push(st,'b');
printf("c进栈\n");Push(st,'c');
printf("d进栈\n");Push(st,'d');
printf("栈%s\n",(StackEmpty(st)==1?"空":"不空"));
GetTop(st,e);
printf("栈顶元素:%c\n",e);
printf("出栈次序:");
while (!StackEmpty(st))
{
Pop(st,e);
printf("%c ",e);
}
printf("\n");
}