#ifndef STACK_H__
#define STACK_H__
#include"head.h"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
struct stack{
ElementType *base;
ElementType *top;
int stackSize;
};
typedef struct stack sqStack;
status initStack(sqStack *S);
status destroyStack(sqStack *S);
status clearStack(sqStack *S);
int length(sqStack S);
boolean empty(sqStack S);
boolean push(sqStack *S,ElementType e);
boolean pop(sqStack *S,ElementType *e);
status getTop(sqStack S,ElementType *e);
void traverse(sqStack S,void (*view)(ElementType*));
#endif
#include"stack.h"
status initStack(sqStack *S)
{
S->base=(ElementType*)malloc(STACK_INIT_SIZE*sizeof(ElementType));
if(!S->base)
exit(OVERFLOW);
S->top=S->base;
S->stackSize=STACK_INIT_SIZE;
return OK;
}
status destroyStack(sqStack *S)
{
free(S->base);
S->base=NULL;
S->top=NULL;
S->stackSize=0;
return OK;
}
status clearStack(sqStack *S)
{
S->top=S->base;
return OK;
}
int length(sqStack S)
{
ElementType *p;
int i=0;
p=S.base;
for(p;p!=S.top;++p)
++i;
return i;
}
boolean empty(sqStack S)
{
return (S.top==S.base)?1:0;
}
boolean push(sqStack *S,ElementType e)
{
if(S->top-S->base>=S->stackSize)//此处注意stackSize有可能扩展过
{
S->base=(ElementType *)realloc(S->base,(S->stackSize+STACKINCREMENT)*sizeof(ElementType));
if(!S->base)
exit(OVERFLOW);
S->top=S->base+S->stackSize;
S->stackSize+=STACKINCREMENT;
}
*S->top++=e;
return OK;
}
boolean pop(sqStack *S,ElementType *e)
{
if(S->top==S->base)
return ERROR;
*e=*--S->top;
return OK;
}
status getTop(sqStack S,ElementType *e)
{
if(S.base==S.top)
return ERROR;
*e=*(S.top-1);//此处并不是要弹出元素,只是获得元素故不能使用*--S.top。
return OK;
}
void traverse(sqStack S,void (*view)(ElementType*))
{
ElementType *p;
p=S.base;
while(p!=S.top)
view(p++);
}
#include<stdio.h>
#include"head.h"
#include"stack.h"
/*
status initStack(sqStack *S);
status destroyStack(sqStack *S);
status clearStack(sqStack *S);
int length(sqStack S);
boolean empty(sqStack S);
boolean push(sqStack *S,ElementType e);
boolean pop(sqStack *S,ElementType *e);
status getTop(sqStack S,ElementType *e);
void traverse(sqStack S,void (*view)(ElementType*));
*/
int main()
{
ElementType a[MAX],e,e1;
int i;
sqStack S;
buildSet(a,MAX,0,100);
printf("show the random array\n");
printSet(a,MAX);
if(initStack(&S))
printf("the address of the stack is :%d\n",S);
if(empty(S))
printf("the stack is empty\n");
for(i=0;i<MAX;i++)
push(&S,a[i]);
printf("traverse the stack after push elements\n");
traverse(S,view);
printf("the length of the stack is :%d\n",length(S));
getTop(S,&e);
printf("the element of the top is :%d\n",e);
pop(&S,&e);
getTop(S,&e1);
printf("the pop elements is %d ,and the new top is %d\n",e,e1);
if(clearStack(&S))
printf("after clear the stack the length of the stack is :%d\n",length(S));
if(destroyStack(&S))
printf("after destroy the stack the address is :%d\n",S.base);
}