#include "stack.h"
Status InitStack(SqStack *s)
{
s->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!s)
{
return MALLOC_ERROR;
}
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
return OK;
}
Status DestroyStack(SqStack *s)
{
if(!s)
{
return ERROR;
}
free(s->base);
s->base=NULL;
s->stacksize=0;
return OK;
}
Status ClearStack(SqStack *s)
{
if(!s||!s->base)
{
return ERROR;
}
memset(s->base,0,s->stacksize*sizeof(SElemType));
s->top=s->base;
return OK;
}
Status ShowStack(SqStack *s)
{
if(!s)
{
return ERROR;
}
if(s->top==s->base)
{
printf("Can't Show,since Stack is Empty!\n");
return ERROR;
}
SElemType *p=NULL;
int num=s->top-s->base;
for(p=s->base;p<s->top;p++)
{
printf("[%d/%d][%c]\t",p-s->base+1,s->top-s->base,*p);
}
printf("\n");
return OK;
}
Status StackEmpty(SqStack *s)
{
if(!s)
{
return ERROR;
}
if(s->base==s->top)
{
return OK;
}
}
int StackLength(SqStack *s)
{
return (s->top - s->base)/sizeof(SElemType);
}
Status GetTop(SqStack *s,SElemType* e)
{
if(!s)
{
return ERROR;
}
*e=*--(s->top);
return OK;
}//Don't Return Local_Var Of The Function,Else The Result Is Not Defined!
Status Push(SqStack *s,SElemType e)
{
if(!s||!s->top)
{
return ERROR;
}
if(s->top - s->base ==STACK_INIT_SIZE-1)
{
printf("Need Realloc!\n");
return ERROR;//Temporary,no deal with it!
}
*(s->top)=e;
s->top++;
return OK;
}
Status Pop(SqStack *s,SElemType* e)
{
if(!s)
{
return ERROR;
}
if(s->top==s->base)
{
printf("Can't pop,since Stack is Empty!\n");
return ERROR;
}
*e=*(s->top--);
return OK;
}
int
main(void)
{
SqStack Stack ,*pStack=&Stack;
SElemType e;
SElemType d;
if(InitStack(pStack)==OK)
{
printf("Init Stack Ok!\n");
}
if(StackEmpty(pStack)==OK)
{
printf("Empty Stack!\n");
}
printf("stack_len:[%d]\n",StackLength(pStack));
if(Push(pStack,'A')==OK)
{
printf("Push Ok!\n");
printf("stack_len:[%d]\n",StackLength(pStack));
}
Push(pStack,'B');
Push(pStack,'C');
Push(pStack,'D');
ShowStack(pStack);
Pop(pStack,&d);
ShowStack(pStack);
Pop(pStack,&d);
ShowStack(pStack);
Push(pStack,'E');
ShowStack(pStack);
Pop(pStack,&d);
ShowStack(pStack);
if(OK==GetTop(pStack,&e))
{
printf("TopElem:[%c]\n",e);
}
if(DestroyStack(pStack)==OK)
{
printf("Destroy Stack Ok!\n");
}
return 0;
}
|