代码实现如下:
#include
#include
#include
#ifndef ERROR
#define ERROR (0)
#endif
#ifndef OK
#define OK (!ERROR)
#endif
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;
typedef struct SqStack{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack, *pStack;
pStack S;
pStack InitStack(pStack S)
{
S = (pStack)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(S == NULL){
return ERROR;
}
S->base = (SElemType *)S;
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return S;
}
pStack Push(pStack S, SElemType e)
{
if((S->top - S->base) >= S->stacksize){
S->base = (SElemType *)realloc(S, (S->stacksize + STACKINCREMENT)*sizeof(SElemType));
if(S->base == NULL)
return ERROR;
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*S->top++ = e;
return S;
}
SElemType GetTop(pStack S)
{
if(S->top == S->base)
return ERROR;
return *(S->top - 1);
}
SElemType Pop(pStack S)
{
if(S->top == S->base)
return 0;
return *(--S->top);
}
int GetLength(pStack S)
{
int length = 0;
if(S->top == S->base)
return 0;
while(S->top-- != S->base)
length++;
return length;
}
int
main(void)
{
int length;
SElemType elm;
S = InitStack(S);
S = Push(S, 3);
S = Push(S, 4);
S = Push(S, 6);
elm = GetTop(S);
printf("the top element of stack S is : %d.\n", elm);
elm = Pop(S);
printf("the top element of stack S is : %d.\n", elm);
elm = Pop(S);
printf("the top element of stack S is : %d.\n", elm);
S = Push(S, 7);
S = Push(S, 8);
length = GetLength(S);
printf("the length of stack S is %d.\n", length);
free(S);
return 0;
}