我想在vip队列中为每个out命令将客户队列出局...直到队列为空时,如果我发出一个OUT命令,它应该开始出列普通队列,直到它为空,如果两个队列都是空的我打印FAILED ............我遇到了Dequeue函数的问题,如果我先将VIP排队,它不会使普通列表出列...但是如果我先将普通列表排队,那么它就不会出现问题。 t使VIP出局。当我调用它时,问题就出现在main中的Dequeue函数中。
#include <stdio.h>
#include <malloc.h>
#include<string.h>
int length=1;//for counting number of customers per day
typedef struct Node//customer details
{
int record;
int CardNum;
char CustomerType[20];
struct Node* next;
}Node;
typedef struct queue
{
Node* front;
Node* rear;
}Queue;
Queue q1,q2;//two queues one vip one ordinary
void Enqueue(Queue *q, int x, char *y);
void Dequeue(Queue *q);
int main()
{
q1.front=NULL;
q2.front=NULL;
q1.rear=NULL;
q2.rear=NULL;
char command[10];
int card;
char client[10];
while(1)
{
scanf("%s",command);
if(strcmp(command,"IN") == 0)
{
printf("IN:");
scanf("%d",&card);
scanf("%s",client);
if(strcmp(client,"VIP")==0)//if client is vip push in queue1
{
Enqueue(&q1,card,client);
}
else if(strcmp(client,"Ordinary")==0)//if client is vip push in queue1
{
Enqueue(&q2,card,client);
}
}
else if(strcmp(command,"OUT") == 0)
{/*i want to dequeue vip queue for every out command when the queue is empty if i make an OUT command it should start to dequeue ordianry untill they are done if both queues are empty i print FAILED*/
if(q1.front == NULL && q1.rear == NULL && q2.front == NULL && q2.rear == NULL)
{
printf("FAILED:\n");
}
else if(strcmp(q1.front->CustomerType,"VIP")==0)
{
Dequeue(&q1);
position1--;
}
else if(strcmp(q2.front->CustomerType,"Ordinary")==0)
{
Dequeue(&q2);
position2--;
}
}
else if(strcmp(command,"QUIT") ==0)
{
printf("GOOD BYE!\n");
break;
}
}
return 0;
}
void Enqueue(Queue *q, int x, char *y)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->CardNum=x;
strcpy(temp->CustomerType,y);
temp->record=length;
temp->next=NULL;
if(q->front == NULL && q->rear == NULL)
{
q->front=q->rear=temp;
}
else
{
q->rear->next=temp;
q->rear=temp;
}
printf("%d %d %s %d\n",temp->record,temp->CardNum,temp->CustomerType);
length++;
}
void Dequeue(Queue *q)
{
Node* temp;
temp=q->front;
if(q->front == q->rear)
{
q->front = q->rear = NULL;
printf("OUT:%d %d %s\n",temp->record,temp->CardNum,temp->CustomerType);
}
else
{
q->front = q->front->next;
printf("OUT:%d %d %s\n",temp->record,temp->CardNum,temp->CustomerType);
}
free(temp);
}
答案 0 :(得分:1)
(这是显然是答案的评论,原始答案不正确)
如果您的VIP队列(q1)为空而普通队列(q2)不为空,则q1.front为空,但尽管您尝试读取q1.front-&gt; CustomerType。这将崩溃或给出未定义的行为。
命名vipQueue和ordinaryQueue而不是q1和q2会使代码更容易理解。