包括构造空栈,销毁栈,把栈置空,检验栈是否为空,求栈的长度,取出栈顶元素,入栈,出栈
#include<stdio.h>
#include<stdlib.h>
#define STACKMAX 100
#define STACKADD 10
#define datatype int
typedef struct
{
datatype *base;
datatype *top;
int stacksize;
}SqStack;
int InitStack(SqStack* S);//初始化,成功返回1
int Destroy(SqStack* S);//销毁栈,成功返回1
int ClearStack(SqStack* S);//把栈置空
int StackEmpty(SqStack* S);//若栈为空返回1,否则返回0
int StackLenth(SqStack* S);//返回栈的元素个数
int GetTop(SqStack* S,datatype* e);//若栈不为空,保存栈顶的元素并返回1;否则返回0
int Push(SqStack* S,datatype e);//插入栈顶元素
int Pop(SqStack* S,datatype* e);//若栈不为空,则删除栈顶元素并保存返回1,否则返回0
int InitStack(SqStack *S)
{
S->base = (datatype*)malloc(STACKMAX*sizeof(datatype));
S->top = S->base;
S->stacksize = STACKMAX;
return 1;
}
int Destroy(SqStack* S)
{
free(S->base);
S->base = NULL;
S->top = NULL;
S->stacksize = 0;
return 1;
}
int ClearStack(SqStack* S)
{
S->base = S->top;
return 1;
}
int StackLenth(SqStack* S)
{
return S->top - S->base;
}
int StackEmpty(SqStack* S)
{
if(S->base == S->top)
return 1;
return 0;
}
int GetTop(SqStack* S,datatype* e)
{
if(StackEmpty(S))
return 0;
*e = *(S->top-1);
return 1;
}
int Push(SqStack* S,datatype e)
{
if(S->top - S->base >= S->stacksize)
{
S->base = (datatype*)realloc(S->base,(S->stacksize+STACKADD)*sizeof(datatype));
if(!S->base)
return 0;
S->top = S->base + S->stacksize;
S->stacksize += STACKADD;
}
*S->top++ = e;
return 1;
}
int Pop(SqStack* S,datatype* e)
{
if(StackEmpty(S))
return 0;
*e = *--S->top;
return 1;
}