我正在尝试实施一个队列,让人们排队等候洗手间,但问题是洗手间是供男性和女性使用的,但是当男性在场时,女性不能进入,当女性在场时,男性不能进入。这是我的问题。(它是我的一个课程的演示,它没有评分,它几乎没有学术性)
我可以将人们插入浴室并进入队列(当一个女性试图进入并且浴室里有一个男人时,她会被添加到队列中)但我不能将人们从队列中取出然后在他们插入时插入浴室有资格进入。这是我的代码。
#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;
}