我不明白这段代码有什么问题。在编译期间没有错误,但在执行 Enqueu 的给定选项时,它会突然停止。问题发生在 Queue->rear->next=NULL 附近,在我看来这是正确的。我不知道我哪里错了。
struct ListNode
{
int data;
struct ListNode *next;
};
struct Queue
{
struct ListNode *front;
struct ListNode *rear;
};
struct Queue *createQueue()
{
struct Queue *Q;
Q=malloc(sizeof(struct Queue));
if(!Q)
return NULL;
Q->front=Q->rear=NULL;
return Q;
}
int IsEmptyQueue(struct Queue *Q)
{
return (Q->front==NULL);
}
int EnQueue(struct Queue *Q,int data)
{
struct ListNode *newNode;
newNode=malloc(sizeof(struct ListNode));
if(!newNode)
return NULL;
newNode->data=data;
newNode->next=NULL;
Q->rear->next=newNode;
Q->rear=newNode;
if(Q->front==NULL)
Q->front=newNode;
}
int main()
{
int choice=0,size,n;
struct Queue *q;
while(1)
{
printf("\nEnter the following");
printf("\n1. Create a queue ");
printf("\n2.Enqueue");
printf("\n7.Exit ");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("\nCreate Queue");
q=createQueue();
break;
case 2:printf("\nInsert");
printf("\nEnter element to be inserted");
scanf("%d",&n);
EnQueue(q,n);
break;
case 7:exit(0);
break;
}
}
}