1、定义栈
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
2、创建一个栈
#define STACK_INIT_SIZE 100
initStack(sqStack *s)
{
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof((ElemType ));
if(!s->base)
exit(0);
s->top = s->base; //最开始,栈顶就是栈底
s->stackSize = STACK_INIT_SIZE; //容量赋值为100
}
3、入栈
#define STACKINCREMENT 10
Push(sqStack *s, ElemType e)
{
if(s->top - s->base >= s->stackSize)
{
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof((ElemType));
if(!s->base)
exit(0);
s->top = s->base + s->stackSize; //最开始,栈顶就是栈底
s->stackSize = s->stackSize + STACKINCREMENT)
}
*(s->top) = e;
s->top ++;
}
4、出栈
Pop(sqStack *s, ElemType *e)
{
if(s->top == s->base)
return;
*e = *--(s->top);
}
5、清空栈:只是清空,内存依然在
ClearStack((sqStack *s)
{
s->top = s->base;
}
6、销毁栈:连栈所在的内存也销毁
DestoryStack((sqStack *s)
{
int i, len;
len = s->stackSize;;
for(i = 0; i < len; i++)
{
free(s->base);
s->base ++;
}
s->base = s->top = NULL;
s->stackSize = 0;
}
7、计算栈的当前容量
int StackLen(sqStack s)
{
return(s.top - s.base);//将两个地址进行相减
}