标签:
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0
#define INIT_SIZE 20
#define INCREMENT_SIZE 10
typedef int Elemtype;
typedef int Status;
typedef struct {
Elemtype *base;//栈尾指针
Elemtype *top;//栈顶指针
int size;
}SqStack;
Status InitStack(SqStack *S)
{
S->base = (Elemtype *)malloc(INIT_SIZE*sizeof(Elemtype));
if(!S->base)
{
exit(OVERFLOW);
}
S->top=S->base;
S->size=INIT_SIZE;
return OK;
}
Status Push(SqStack *S,Elemtype e)
{
if((S->top-S->base)/sizeof(Elemtype)>=S->size)
{
S->base=(Elemtype *)realloc(S->base,(S->size+INCREMENT_SIZE)*sizeof(Elemtype));
if(!S->base)
{
exit(OVERFLOW);
}
S->top=S->base+S->size*sizeof(Elemtype);
S->size+=INCREMENT_SIZE;
}
*S->top=e;
S->top+=sizeof(Elemtype);
return OK;
}
Status Pop(SqStack *S,Elemtype *e)
{
if(S->top==S->base)
{
printf("The stack is empty\n");
return ERROR;
}
else
{
S->top-=sizeof(Elemtype);
*e=*S->top;
return OK;
}
}
Status TraverseStack(SqStack *S)
{
while(S->top>S->base)
{
printf("%d\n",*S->base);
S->base+=sizeof(Elemtype);
}
return OK;
}
int main()
{
int i;
int a;
SqStack S;
int ret=InitStack(&S);
if(ret)
{
printf("init_success\n");
}
else
{
printf("init_error\n");
}
for(i=0;i<10;i++)
{
Push(&S,i+1);
}
TraverseStack(&S);
return 0;
}
标签:
原文地址:http://www.cnblogs.com/loveyan/p/4556536.html