#include
#include
#define max 6
typedef struct Stack
{
int arr[max];
int val;
int top;
}stack;
stack *pst;
int isfull(stack *p)
{
if(p->top==max-1)
return 0;
else
return 1;
}
void push(stack *p,int data)
{
if(isfull(p))
{
p->arr[++(p->top)]=data;
}
}
int isempty(stack *p)
{
if(p->top==-1)
return 1;
else
return 0;
}
int pop(stack *p)
{
if(isempty(p))
{
return (p->arr[p->top--]);
}
}
int main()
{
pst=(stack*)malloc(sizeof(struct Stack));
pst->top=-1;
int num,r;
int i;
for(i=0;iscanf("%d",&num);
push(pst,num);
}
for(i=0;ipop(pst);
printf("%d ",r);
}
}
顺序栈的初始、判满、入栈、判空、出栈、打印,为什么打印出来的都是0?
isfull判断反了吧,
if(p->top==max-1)
return 1;
else
return 0;
修改如下,供参考:
#include <stdio.h>
#include <stdlib.h>
#define max 6
typedef struct Stack
{
int arr[max];
int val;
int top;
}stack;
stack* pst;
int isfull(stack* p)
{
return p->top == max - 1; //修改
//if (p->top == max - 1)
// return 0;
//else
// return 1;
}
void push(stack* p, int data)
{
if (!isfull(p)) //if (isfull(p)) 修改
{
p->arr[++(p->top)] = data;
}
}
int isempty(stack* p)
{
return p->top == -1; //修改
//if (p->top == -1)
// return 1;
//else
// return 0;
}
int pop(stack* p)
{
if (!isempty(p)) //if (isempty(p)) 修改
{
return (p->arr[p->top--]);
}
else //修改
return -1; //修改
}
int main()
{
pst = (stack*)malloc(sizeof(struct Stack));
pst->top = -1;
int num, r;
int i;
for (i = 0; i < max; i++)
{
scanf("%d", &num);
push(pst, num);
}
for (i = 0; i < max; i++)
{
r = pop(pst);
if (r == -1) //修改
printf("stack is empty.");
else
printf("%d ", r);
}
}
找到原因了:第37行改为!empty
另外,可以参考楼上回答对程序进行完善优化。
2023/4/20,加油