#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -1
#define OK 1
#define ERROR 0
typedef int Status;
typedef int SElemType;
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) exit(OVERFLOW);
S->top=S->base;
S->stacksize=STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack *S,SElemType e)
//插入元素e为新的栈顶元素
{
if(S->top-S->base>=S->stacksize)
{
S->base=(SElemType*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S->base) exit(OVERFLOW);
S->top=S->base+S->stacksize;
S->stacksize+=STACKINCREMENT;
}
*S->top++=e;
return OK;
}
Status Pop(SqStack *S,SElemType *e)
//用e返回栈顶元素并删除栈顶元素
{
if(S->top==S->base)
return ERROR;
*e=*--S->top;
return OK;
}
Status GetTop(SqStack S,SElemType *e)
//返回栈顶元素
{
if(S.top==S.base)
return ERROR;
*e=*(--S.top);
return OK;
}
Status StackEmpty(SqStack S)
//若栈为空,返回OK,否则返回ERROR
{
if(S.top==S.base)
return OK;
else
return ERROR;
}
int StackLength(SqStack S)
//返回栈的长度
{
return (S.top-S.base);
}
Status PrintElem(SElemType e)
//visit指针函数的调用
{
printf("%d\t",e);
return OK;
}
Status StackTraverse(SqStack S,Status(*visit)(SElemType))
//栈的遍历
{
SElemType *p;
p=S.base;
while(p!=S.top)
{
if(!visit(*p))
return ERROR;
p++;
}
return OK;
}
Status ClearStack(SqStack *S)
//置为空栈
{
S->top=S->base;
return OK;
}
Status DestroyStack(SqStack *S)
//销毁栈
{
free(S->base);
S->base=NULL;
S->top=NULL;
S->stacksize=0;
return OK;
}
int main()
{
SqStack S;
SElemType *e;
int n,i;
InitStack(&S);
printf("请输入需要入栈的数据个数\n");
scanf("%d",&n);
for(i=0;i {
scanf("%d",e);
Push(&S,*e);
}
printf("栈的遍历\n");
StackTraverse(S,PrintElem);
printf("\n栈的长度为:\n");
printf("%d",StackLength(S));
printf("\n返回栈首元素:\n");
GetTop(S,e);
printf("%d",*e);
printf("\n元素出栈后\n");
while(!StackEmpty(S))
{
Pop(&S,e);
printf("%d\t",*e);
}
printf("\n\t\t\t杨佳宁制作");
return 0;
}