顺序存储
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define SElemType int
#define Status int
#define TRUE 1
#define FALSE 0
typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
Status 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;
return OK;
}
Status Push(SqStacks *S,SElemType e) {
if(S->top->S->base >= S->stacksize){
S->base = (SElemType * )realloc(S->base,(S->stacksize +STACKINCREMENT) * sizeof(SElemType));
if(!S->base) return ERROR;
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top++) = e;
return OK;
}
Status GetTop (SqStack S,SElemType *e) {
if(S.top == S.base) return ERROR;
*e = *(S->top-1);
return OK;
}
Status Pop (SqStack *S,SElemType *e) {
if(S->top == S->base) return ERROR;
*e = *--S->top;
return OK;
}
Status StackLength (SqStack S) {
int len;
len = S.top-S.base;
return len;
}
Status StackEmpty(SqStack S)
{
if(S.top == S.base)
return TRUE;
else
return FALSE;
}
Status ClearStack(SqStack *S) {
if(S->top==S->base) return OK;
else{
for(;S->top>S->base;S->top--);
}
return OK;
}
Status StackTraverse(SqStack S) {
if(S.top == S.base)
return ERROR;
else{
for(;S.top>S.base;S.base++)
printf("%d ",*(S.base));
}
return OK;
}
int main(void)
{
SElemType a;
SElemType b;
SqStack S;
InitStack(&S);
printf("%d ",StackEmpty(S));
Push(&S,0);
Push(&S,1);
Push(&S,2);
Push(&S,3);
Push(&S,4);
Push(&S,5);
Push(&S,6);
printf("\n");
StackTraverse(S);
printf("\n");
printf("%d ",StackEmpty(S));
GetTop(S,&a);
Pop(&S,&b);
Pop(&S,&b);
printf("\n");
StackTraverse(S);
printf("\n");
printf("%d ",a);
printf("%d ",b);
printf("%d ",StackLength(S));
ClearStack(&S);
printf("%d ",StackEmpty(S));
return 0;
}