#include<stdio.h>
#include<stdlib.h>
#define LENGTH 100 //堆的初始分配的长度
#define ADD_LEN 10 //堆栈增量
typedef struct
{//构造栈的数据类型
int *base;
int *top;
int stacksize;
}SqStack;
void CreateStack(SqStack &S);//初始化一个栈
void PushStack(SqStack &S,int e);//e进栈
void PopStack(SqStack &S);//栈顶元素出栈
void DestroyStack(SqStack &S);//销毁栈
void PrintfStack(SqStack &S);//输出当前的栈
void main()
{ SqStack Sa;
int m,n;
CreateStack(Sa);
printf("Please input the total of inserting number:");
scanf("%d",&m);
while(m>LENGTH)
{ printf("The number you input can't be larger than %d。please input again:\n",LENGTH);
scanf("%d",&m);
}
while(m--)
{ printf("Please input a number to insert:");
scanf("%d",&n);
PushStack(Sa,n);
}
PrintfStack(Sa);
PopStack(Sa);
PrintfStack(Sa);
DestroyStack(Sa);
}
void CreateStack(SqStack &S)
{ S.base=(int *)malloc(LENGTH*sizeof(int));
if(!S.base)
{ printf("Fail to create stack!\n");
return;
}
S.top=S.base;
S.stacksize=LENGTH;
printf("Success to create stack!\n");
}
void PushStack(SqStack &S,int e)
{ if(S.top-S.base>=S.stacksize)//考虑栈是否已满,如满,则从新分配空间
{ S.base=(int *)realloc(S.base,(S.stacksize+ADD_LEN)*sizeof(int));
if(!S.base)
return;
S.top=S.base+S.stacksize;
S.stacksize+=ADD_LEN;
}
*S.top++=e;
printf("%d success to insert the stack!\n",e);
}
void PopStack(SqStack &S)
{ int m;
if(S.top==S.base)
{ printf("The stack is empty!\n");
return;
}
m=*--S.top;
printf("%d is out of the stack!\n",m);
}
void DestroyStack(SqStack &S)
{ free(S.base);//释放空间
S.base=NULL;
*S.top=-1;//将其它成员设置成安全值
S.stacksize=0;
printf("Success to destroy the stack!\n");
}
void PrintfStack(SqStack &S)
{ int *p;
p=S.top;
printf("The stack is :");
while(--p>=S.base)
printf("%d",*p);
printf("\n");
}