gpt4 book ai didi

c - 使用链表实现简单队列

转载 作者:行者123 更新时间:2023-11-30 15:49:20 24 4
gpt4 key购买 nike

我正在尝试实现一个队列,让人们排队等候洗手间,但问题是洗手间是男女皆宜的,但当男性在场时,女性无法进入,而当女性在场时,男性无法进入无法进入。这是我的问题。 (这是我的一门类(class)的演示,它没有评分,几乎没有学术性)

我可以将人员插入浴室并插入队列(当一名女性尝试进入并且浴室中有一名男性时,她会被添加到队列中),但我无法将人员从队列中取出然后插入队列中卫生间(当他们有资格进入时)。这是我的代码。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

struct Node
{
int Data;
struct Node* next;
}*rear, *front;

void delQueue()
{
struct Node *temp, *var=rear;
if(var==rear)
{
rear = rear->next;
free(var);
}
else
printf("\nQueue Empty");
}

void push(int value)
{
struct Node *temp;
temp=(struct Node *)malloc(sizeof(struct Node));
temp->Data=value;
if (front == NULL)
{
front=temp;
front->next=NULL;
rear=front;
}
else
{
front->next=temp;
front=temp;
front->next=NULL;
}
}

void display()
{
struct Node *var=rear;
if(var!=NULL)
{
printf("\nElements in queue are: ");
while(var!=NULL)
{
printf("\t%d",var->Data);
var=var->next;
}
printf("\n");
}
else
printf("\nQueue is Empty\n");
}

int main() {

int man_busy = 0;
int woman_busy = 0;
int input = 0;
int i = 0;

printf("\n(1) Man enters\n");
printf("(2) Woman enters\n");
printf("(3) Man leaves\n");
printf("(4) Woman leaves\n");


printf("\nEmpty!\n");


for(i=0; i<20; i++) {

scanf("%d", &input);

if(input == 1){
if(woman_busy > 0){
printf("Man Can't enter when women are present\n");
printf("You will have to wait in the queue\n");
push(input);
display();
}
else if(woman_busy == 0) {
man_busy = man_busy + 1;
printf("Occupied By Man: %d\n", man_busy);
}
}
else if(input == 2) {
if(man_busy > 0){
printf("Woman Can't enter when men are present\n");
printf("You will have to wait in the queue\n");
push(input);
display();
}
else if(man_busy == 0) {
woman_busy = woman_busy + 1;
printf("Occupied By Woman: %d\n", woman_busy);
}
}
else if(input == 3) {
man_busy = man_busy - 1;
if (man_busy == 0 && woman_busy == 0){
printf("Empty!\n");
delQueue();
display();
}
else if (man_busy < 0) {
printf("Invalid command!\n");
man_busy = man_busy + 1;
}
else {
printf("Occupied By Man: %d\n", man_busy);
}
}
else if(input == 4) {
woman_busy = woman_busy - 1;
if (man_busy == 0 && woman_busy == 0) {
printf("Empty!\n");
delQueue();
display();
}
else if (woman_busy < 0) {
printf("Invalid command!\n");
woman_busy = woman_busy + 1;
}
else {
printf("Occupied By Woman: %d\n", woman_busy);
}
}
}
return 0;

}

最佳答案

您需要一个例程出队(我建议函数名称入队和出队,因为堆栈使用推/弹出命名法)。

当条件浴室为空时,如果队列不为空,则需要将第一个元素类型的所有元素出队(即,根据第一个元素是男性还是女性,所有男性或所有女性)队列)并将它们放入浴室内。当浴室空时重复此操作。

关于c - 使用链表实现简单队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16369131/

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