#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 100
#define STACK_REALLOC_SIZE 4
typedef int State;
typedef int SElemType;
typedef struct SqStack
{
SElemType *top;
SElemType *base;
int stackSize;
}SqStack;
State initStack(SqStack *S);
State destroyStack(SqStack *S);
State pushStack(SqStack *S, int e);
State popStack(SqStack *S, int *e);
int StackLen(SqStack S);
State printStack(SqStack S);
int StackLen(SqStack S)
{
return S.top - S.base;
}
State initStack(SqStack *S)
{
S->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S->base)
return ERROR;
S->top = S->base;
S->stackSize = STACK_INIT_SIZE * sizeof(SElemType);
return OK;
}
State pushStack(SqStack *S, int e)
{
if (S->top - S->base >= S->stackSize)
{
realloc(S->base, S->stackSize + STACK_REALLOC_SIZE * sizeof(SElemType));
if (!S->base)
return ERROR;
S->stackSize = S->stackSize + STACK_REALLOC_SIZE * sizeof(SElemType);
}
*(S->top)++ = e;
return OK;
}
State popStack(SqStack *S, int *e)
{
if (S->top == S->base)
return ERROR;
*e = *--S->top;
return OK;
}
State destroyStack(SqStack *S)
{
free(S->base);
S->top = NULL;
S->base = NULL;
S->stackSize = 0;
return OK;
}
State printStack(SqStack S)
{
while (S.top != S.base)
{
printf("%d ", *--S.top);
}
return OK;
}
int main(void)
{
SqStack s;
int e;
initStack(&s);
pushStack(&s, 1);
pushStack(&s, 2);
pushStack(&s, 3);
popStack(&s, &e);
pushStack(&s, 4);
printf("弹栈了 %d, 目前栈长 %d\n", e, StackLen(s));
printStack(s);
destroyStack(&s);
return 0;
}