gpt4 book ai didi

c - 从堆栈弹出时输出错误

转载 作者:行者123 更新时间:2023-12-02 22:01:58 28 4
gpt4 key购买 nike

我已经使用堆栈编写了一个程序,但是我得到的输出有点错误。我得到的输出有我需要的答案,还有 2 个非预期的值。

这是我所做的:

#include <stdio.h>
#include<malloc.h>
#define MAX 180

struct cakes{
int spongecake;
int meringue;
int chocalate;
int red_velvet;
struct cakes *next;
};

struct stack{
int top;
int cake[10];
};

int isFull(struct stack *);
int isEmpty(struct stack *);
void push(struct stack *,int);
int pop(struct stack *);

void order_out(struct cakes *);

main()
{
struct cakes *head;

head=(struct cakes *)malloc(sizeof(struct cakes));
cake_order(head); //this is a seperate function, it works perfectly.
head->next=(struct cakes *)malloc(sizeof(struct cakes));
order_out(head->next);
}

int isFull(struct stack *q)
{
if(q->top==10-1)
{
return 1;
}
else
{
return 0;
}
}

void push(struct stack *sptr,int x)
{
if(!isFull(sptr))
{
sptr->top++;
sptr->cake[sptr->top]=x;
}
}

int isEmpty(struct stack *q)
{
if(q->top==-1)
{
return 1;
}
else
{
return 0;
}

}

int pop(struct stack *sptr)
{
int ret=NULL;
if(!isEmpty(sptr))
{
ret=sptr->cake[sptr->top];
sptr->top--;
return ret;
}
}

void order_out(struct cakes *theorder)
{
struct stack s;
s.top=-1;
int k=0;
int i=0;
int p=0;
int r=0;
int value1,value2;
int items[10];

theorder->spongecake=1;
theorder->meringue=2;
theorder->chocalate=3;
theorder->red_velvet=4;

for(;i<10;i++)
{
push(&s,theorder->spongecake);

push(&s,theorder->meringue);
push(&s,theorder->chocalate);
push(&s,theorder->red_velvet);
}

while(!isEmpty(&s))
{
printf("\n%d",pop(&s));
}
}

我得到的输出如下: enter image description here

如您所见,它首先打印 2 和 1。似乎是什么问题?

最佳答案

在我看来你的程序运行如下,

下面的循环尝试插入 40 个值,

for(;i<10;i++)
{
push(&s,theorder->spongecake);
push(&s,theorder->meringue);
push(&s,theorder->chocalate);
push(&s,theorder->red_velvet);
}

但由于您在 isFull() 函数中声明了 if(q->top==10-1),所以只插入了 10 个值。即计数器从 0 到 9 计数 10 个元素。元素被压入的顺序如下 1, 2, 3, 4, 1, 2, 3, 4, 1, 2。这些元素在弹出时会给出序列 2, 1, 4, 3, 2, 1, 4, 3, 2, 1。因此,您获得的输出实际上是正确的,或者至少不是异常。

还有几个问题我想指出,

函数pop()应该如下所示,

 int pop(struct stack *sptr)
{
int ret=NULL;
if(!isEmpty(sptr))
{
ret=sptr->cake[sptr->top];
sptr->top--;
return ret;
}
return 0;
}

否则当 sptr 为空时函数返回随机值。

语句if(q->top==10-1)应该是if(q->top==9)

关于c - 从堆栈弹出时输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16798607/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com