top为整数且指向栈顶元素,S->top=-1,具体入栈如下所示:
一、栈的静态分配顺序存储结构描述:
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define MAXSIZE 10
typedef int Elemtype;
typedef int Status;
typedef struct SqStack{
Elemtype elem[MAXSIZE];//定义一个存放栈数据元素的一维数组
int top; //栈顶指针
}SqStack;
二、栈的初始化:
/*栈的静态分配顺序存储,top为整数且指向栈顶元素*/
void InitStack(SqStack *S)
{
S->top=-1;
}
三、入栈(压栈)操作:
/*入栈(压栈)操作*/
Status PushStack(SqStack *S,Elemtype e)
{
if(S->top >= MAXSIZE-1)
{
return ERROR;
}
S->elem[++S->top]=e;
return OK;
}
四、判断是否栈空:
/*判断栈是否为空*/
Status StackEmpty(SqStack *S)
{
if(S->top == -1)
{
return OK;
}
return ERROR;
}
五、取栈顶元素:
/*取栈顶元素*/
Status GetTop(SqStack *S,Elemtype *e)
{
if(S->top != -1)
{
*e=S->top;
return OK;
}
return ERROR;
}
六、清空栈:
/*清空栈*/
void ClearStack(SqStack *S)
{
S->top=-1;
}
七、销毁栈:
/*销毁栈*/
void DestroyStack(SqStack *S)
{
if(S->top != -1)
{
S->top=-1;
}
}
八、出栈(弹栈)操作:
/*出栈(弹栈)操作*/
Status PopStack(SqStack *S,Elemtype *e)
{
if( S->top == -1 )
{
return ERROR;
}
*e=S->elem[S->top--];
return OK;
}
九、遍历栈:
/*利用回调函数遍历栈*/
void StackTraverse(SqStack S,void(*visit)(Elemtype))
{
int i=0;
while(i<=S.top)
{
visit(S.elem[i++]);
}
}
void Print(Elemtype e)
{
printf("%d ",e);
}
十、主函数:
int main()
{
int i,e,value;
SqStack S;
InitStack(&S);
for(i=0;i < MAXSIZE;i++)
{
value=PushStack(&S,i);
if(!value)
{
printf("超出栈的存储范围!\n");
return ERROR;
}
}
printf("栈的初始化元素为:\n");
StackTraverse(S,Print);
printf("\n栈长为:%d\n",S.top+1);
value=PopStack(&S,&e);
if(!value)
{
printf("空栈!\n");
return ERROR;
}
printf("\n弹出的栈顶元素为:%d\n",e);
value=StackEmpty(&S);
if(!value)
{
printf("非空栈!\n");
}
else
{
printf("空栈!\n");
}
value=GetTop(&S,&e);
if(value)
{
printf("新的栈顶元素为:%d",e);
}
else
{
printf("空栈!\n");
return ERROR;
}
printf("\n弹出栈顶元素后栈的遍历为:\n");
StackTraverse(S,Print);
printf("\n栈长为:%d\n",S.top+1);
printf("\n清空栈后:");
ClearStack(&S);
value=StackEmpty(&S);
if(!value)
{
printf("\n非空栈!");
}
else
{
printf("\n空栈!\n");
}
printf("栈长为:%d\n",S.top+1);
return 0;
}
十一、运行效果截图: