View Code
#include <stdio.h>
#include <stdlib.h>

#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2

typedef int SElemType;

struct SqStack{
SElemType *base;
SElemType *top;
int stacksize;
};

#define SqStack struct SqStack

int InitStack(SqStack *S)
{
if ( !(S->base = (SElemType *) malloc (STACK_INIT_SIZE * sizeof(SElemType))))
exit(3);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return 1;
}

int DestroyStack(SqStack *S)
{
free((*S).base);
(*S).base=NULL;
(*S).top=NULL;
(*S).stacksize=0;
return 1;

}

int ClearStack(SqStack *S)
{
S->top=S->base;
return 1;
}

int StackEmpty(SqStack *S)
{
if((*S).top == (*S).base )
return 1;
else
return 0;

}

int StackLength(SqStack *S)
{
return S->top - S->base;
}

int GetTop(SqStack *S,SElemType *e)
{
if(S->top>S->base)
{
*e=*(S->top - 1);
return 1;
}else
return 0;
}

int Push(SqStack *S,SElemType e)
{
if ( S->top - S->base >= S->stacksize )
{
S->base=(SElemType *) realloc (S->base,(S->stacksize + STACKINCREMENT) * sizeof(SElemType));
if(!S->base)
exit(3);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top)++=e;
return 1;
}

int Pop(SqStack *S,SElemType *e)
{
S->base = S->base -12;
if(S->top == S->base)
return 0;
*e=*--(S->top);
return 1;
}

int StackTraverse(SqStack *S,int (*visit)(SElemType))
{
while(S->top > S->base){
visit(*(S->base)++);
}
printf("\n");
return 1;
}

int visit(SElemType c)
{
printf("%d ",c);
return 1;
}

int main(){
int j;
SqStack s;
SElemType e;
if(InitStack(&s) == 1 )
for( j=1; j <= 12;j++)
Push(&s,j);
printf("the elem is");
StackTraverse(&s,visit);
Pop(&s,&e);
printf("S.top: %d is out\n",e);
printf("stack null? %d (1:yes,0:n)\n",StackEmpty(&s));
GetTop(&s,&e);
printf("S.top is %d ,the length of stack is %d\n",e,StackLength(&s));
ClearStack(&s);
printf("after clean stack, is the stack null?%d(1:yes,0:no)\n",StackEmpty(&s));
DestroyStack(&s);
printf("after destroy stack, S.top = %u S.base = %u S.stacksize = %d\n",s.top,s.base,s.stacksize);
}
posted on 2011-11-24 16:26  hotty  阅读(104)  评论(0)    收藏  举报