#include<stdio.h>
#include<malloc.h>
#define MaxSize 5
typedef int ElemType;
typedef struct
{ ElemType data[MaxSize];
int top;
}SqStack; //表示这个顺序栈中有多个元素
//初始化栈
SqStack *InitStack()
{ SqStack *s;
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1; //因为规定,top=-1,表示栈空
return s;
}
//入栈
bool Push(SqStack *s,ElemType e)
{
if (s->top==MaxSize-1) //因为top从0开始计数;
return false;
s->top++;
s->data[s->top]=e;
return true;
}
//出栈
ElemType Pop(SqStack *s)
{ ElemType e;
e=s->data[s->top];
s->top--;
return e;
}
//显示栈中的内容
void DispStack(SqStack *s)
{ int top;
top=s->top;
while(top>-1)
{
printf(" %d ",s->data[top]);
top--;
}
}
int main()
{
SqStack *InitStack();
bool Push(SqStack *s,ElemType e);
void DispStack(SqStack *s);
ElemType a,x,y; //函数申明
SqStack *s;
s=InitStack();
printf("输入0代表结束程序,若1则入栈");
scanf("%d",&a);
while(a!=0)
{
if(a==1)
{
infinite_loop: printf("请输入要入栈的数:");
scanf("%d",&x);
Push(s,x);
printf("当前栈元素为:");
DispStack(s);
printf("是否继续入栈,1入栈 2出栈:");
scanf("%d",y);
if(y==1) goto infinite_loop;
if(y==2) goto infinite_end;
}
infinite_end: Pop(s);
printf("当前栈元素为:");
DispStack(s);
}
return 0;
}
//大一生要求就是输入数入栈,然后每次显出栈内元素并询问是否继续,栈满了要提示并退出
scanf("%d", &y); //你的少写一个&
修改如下,供参考:
#include <stdio.h>
#include <malloc.h>
#define MaxSize 5
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack; //表示这个顺序栈中有多个元素
//初始化栈
SqStack* InitStack()
{
SqStack* s;
s = (SqStack*)malloc(sizeof(SqStack));
s->top = -1; //因为规定,top=-1,表示栈空
return s;
}
//入栈
bool Push(SqStack* s, ElemType e)
{
if (s->top == MaxSize - 1) { //因为top从0开始计数;
printf("栈已满!\n"); //修改
return false;
}
s->top++;
s->data[s->top] = e;
return true;
}
//出栈
ElemType Pop(SqStack* s)
{
ElemType e;
if (s->top == -1) { //栈空 //修改
printf("栈已空!\n"); //修改
return false;
}
e = s->data[s->top];
s->top--;
return e;
}
//显示栈中的内容
void DispStack(SqStack* s)
{
int top;
top = s->top;
while (top > -1)
{
printf(" %d ", s->data[top]);
top--;
}
printf("\n"); //修改
}
int main()
{
//SqStack* InitStack();
//bool Push(SqStack * s, ElemType e);
//void DispStack(SqStack * s);
ElemType a = 1, x, y; //函数申明 //修改
SqStack* s;
s = InitStack();
//printf("输入0代表结束程序,若1则入栈");
//scanf("%d", &a);
while (a)
{
printf("请输入选择( 0.结束程序 1.入栈 2.出栈 ):"); //修改
scanf("%d", &a);
switch (a) { //修改
case 1:
//infinite_loop:
printf("请输入要入栈的数:");
scanf("%d", &x);
Push(s, x);
printf("当前栈元素为:");
DispStack(s);
//printf("是否继续入栈,1入栈 2出栈:");
//scanf("%d", y);
//if (y == 1) goto infinite_loop;
//if (y == 2) goto infinite_end;
break;
case 2:
//infinite_end:
x = Pop(s);
if(x!=0){
printf("当前出栈元素为:");
printf("%d\n", x); //DispStack(s);
}
break;
case 0:
break;
default:
break;
}
}
return 0;
}