我已经使用堆栈制作了一个程序,但是我得到的输出有点错误。我得到的输出有我需要的答案,也有 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));
}
}
我得到的输出如下:
如您所见,它首先打印 2 和 1。似乎是什么问题?