gpt4 book ai didi

c - 根据条件从队列中删除

转载 作者:行者123 更新时间:2023-11-30 17:51:19 26 4
gpt4 key购买 nike

我有一个带有队列的程序,我需要根据条件从队列中删除值。条件是

If the value which was removed previously from the queue is more than the value which is going to to removed, then the value should be removed from the queue, if not the value is put back in to the queue again (Circular implementation).

这是我到目前为止所做的:

    #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);
}
}
}

我无法获得所需的输出,这里的问题是什么?

感谢您的宝贵时间。

最佳答案

在 while 循环中,当您只想删除最多一个元素时,可以多次调用removes(&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()的这种情况。

关于c - 根据条件从队列中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16785272/

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