我有一个带队列的程序,我需要根据条件从队列中删除值。条件是
如果先前从队列中删除的值大于要删除的值,则应从队列中删除该值, 如果不是,则将值重新放回队列中(循环实现)。
这是我到目前为止所做的:
#include<stdio.h>
#include<malloc.h>
#define MAX 180
struct cakes{
int spongecake;
int meringue;
int chocalate;
int red_velvet;
struct newcake *next;
};
struct Queue{
int front;
int rear;
int count;
int cake[10];
};
void order_out(struct cakes *);
void init(struct Queue *);
int isFull(struct Queue *);
void insert(struct Queue *,int);
int isEmpty(struct Queue *);
int removes(struct Queue *);
main()
{
struct cakes *head;
head=(struct cakes*)malloc(sizeof(struct cakes));
order_out(head);
}
void init(struct Queue *q)
{
q->front=0;
q->rear=10-1;
q->count=0;
}
int isFull(struct Queue *q)
{
if(q->count==10)
{
return 1;
}
else
{
return 0;
}
}
void insert(struct Queue *q,int x)
{
if(!isFull(q))
{
q->rear=(q->rear+1)%10;
q->cake[q->rear]=x;
q->count++;
}
}
int isEmpty(struct Queue *q)
{
if(q->count==0)
{
return 1;
}
else
{
return 0;
}
}
int removes(struct Queue *q)
{
int caked=NULL;
if(!isEmpty(q))
{
caked=q->cake[q->front];
q->front=(q->front+1)%10;
q->count--;
return caked;
}
}
void order_out(struct cakes *theorder)
{
struct Queue s;
int i,k;
int p=0;
theorder->spongecake=20;
theorder->meringue=75;
theorder->chocalate=40;
theorder->red_velvet=30;
k=theorder->chocalate;
init(&s);
for(i=0;i<10;i++)
{
insert(&s,theorder->chocalate);
insert(&s,theorder->spongecake);
insert(&s,theorder->meringue);
insert(&s,theorder->red_velvet);
}
while(!isEmpty(&s))
{
if(k>removes(&s)) //here i check whether the the value am going to remove is less than the chocalate value
{
printf("%d",removes(&s));
k=removes(&s); //i make k the value which was removed so it will be compared in the next time.
}
else
{
p=removes(&s);
insert(&s,p);
}
}
}
我无法获得所需的输出,这似乎是什么问题?
感谢您的时间。
答案 0 :(得分:0)
只需获取变量并将其值初始设置为零。
在删除之前的pop函数中,只需检查是否
值&lt;变量强>
。 如果为true,则POP else返回。
答案 1 :(得分:0)
在你的while循环中,当你只想删除一个元素时,你会多次调用remove(&amp; s)。
对于你的情况,while循环可以是:
while(!isEmpty(&s))
{
int tmp=removes(&s);
if(k>tmp) {
printf("%d should be remove,and k is %d\n",tmp,k);
k = tmp;
printf("k changed.\n");
}
else
{
printf("%d insert again,and k is %d\n",tmp,k);
insert(&s,tmp);
}
}
不幸的是,由于您的情况和数据,这是一个无限循环。
在您的初始队列中,
40 20 75 30 40 20 75 30 40 20 75 30
k = 40,再次插入40次。
到20,删除20,现在k = 20.
其余的不少于20,他们会一遍又一遍地检查和插入。
另外,即使队列为空,你的remove()也应该返回一个错误的值,因为你处理这种情况你调用了remove()。