顺序栈
#include <stdio.h>
#define MAXSIZE 15//符号常量,代表线性表存储空间初始分配量
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int SElemType;//SElemType这里假设为int,可以根据需要进行更改
typedef int Status;//Status是函数的类型,其值是函数结果状态代码,如OK等
typedef struct sqStack//顺序栈结构
{
SElemType data[MAXSIZE];//数组,存储数据元素
int top; //用于栈顶指针
}SqStack;
/*构造一个空栈S*/
Status InitStack(SqStack *S)
{
S->top=-1;
return OK;
}
/*插入元素e为新的栈顶元素*/
Status Push(SqStack *S,SElemType e)
{
if(S->top == MAXSIZE - 1)//栈满
return ERROR;
S->data[++S->top]=e;
return OK;
}
/* 从栈底到栈顶依次对栈中每个元素显示 */
Status StackTraverse(SqStack S)
{
int i;
i=0;
while(i<=S.top)
{
printf("%d ",S.data[i++]);
}
printf("\n");
return OK;
}
/*若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR*/
Status Pop(SqStack *S,SElemType *e)
{
if(S->top==-1)//栈空
return ERROR;
*e=S->data[S->top--];
return OK;
}
/*若栈S为空栈,则返回TRUE,否则返回FALS */
Status StackEmpty(SqStack S)
{
if(S.top==-1)
return TRUE;
else
return FALSE;
}
/*若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR*/
Status GetTop(SqStack S,SElemType *e)
{
if(S.top==-1)
return ERROR;
else
*e=S.data[S.top];
return OK;
}
/*返回S的元素个数,即栈的长度*/
int StackLength(SqStack S)
{
return S.top+1;
}
/*把S置为空栈*/
Status ClearStack(SqStack *S)
{
S->top=-1;
return OK;
}
int main()
{
SqStack s;
int j;
SElemType e;
if(InitStack(&s)==OK)
{
for(j=1;j<=10;j++)
Push(&s,j);
}
printf("栈中元素依次为:");
StackTraverse(s);
Pop(&s,&e);
printf("弹出的栈顶元素e = %d\n",e);
printf("栈中元素依次为:");
StackTraverse(s);
printf("栈空否:%d(1:空 0:否)\n",StackEmpty(s));
GetTop(s,&e);
printf("栈顶元素e = %d,栈的长度为%d\n",e,StackLength(s));
ClearStack(&s);
printf("清空栈后,栈空否:%d(1:空 0:否)\n",StackEmpty(s));
return 0;
}