数据结构实验 栈子系统
#include<>
#include<>
#include<>
#include<algorithm>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S)
{
S.base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base)
{
printf("存储分配失败!\n");
return 0;
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return 1;
}
int Push(SqStack &S,SElemType e){
if(S.top - S.base >= S.stacksize){
S.base = (SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base)
return 0;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return 1;
}
int vi(SElemType e)
{
printf("%d ", e);
return 1;
}
int Pop(SqStack &S,SElemType &e){
if(S.top == S.base)
return 0;
e = *--S.top;
return 1;
}
int StackTraverse(SqStack S, int(*visit)(SElemType))
{
SElemType e;
printf("遍历栈中元素: ");
while(S.top != S.base)
{
S.top--;
e = *S.top;
if(!(*visit)(e))
{
return 0;
}
}
printf("\n");
return 1;
}
void main(){
SqStack S;
int j=1,e,n,i;
int choose;
while(j)
{
printf("\n\t\t------------栈子系统----------");
printf("\n\t\t*\t 1----创建栈\t\t\t*");
printf("\n\t\t*\t 2----栈顶插入\t\t\t*");
printf("\n\t\t*\t 3----栈顶删除\t\t\t*");
printf("\n\t\t*\t 4----展示\t\t\t*");
printf("\n\t\t*\t 0----退出\t\t\t*");
printf("\n\t\t请选择菜单号码\t\t\t*");
scanf("%d",&choose);
printf("\n");
if(choose == 1)
{
InitStack(S);
printf("建栈成功\n");
}
else if(choose == 2)
{
printf("输入插入的数量:");
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
printf("输入第%d个的值:",i+1);
scanf("%d",&e);
Push(S,e);
}
}
else if(choose == 3)
{
Pop(S,e);
printf("%d",e);
}
else if(choose == 4)
{
StackTraverse(S,vi);
}
else if(choose == 0)
{
j = 0;
}
else
printf("输入错误!\n");
}
}