我不明白这段代码有什么问题。编译期间没有错误,但在执行 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;
}
}
}
最佳答案
当队列为空时,其front
和rear
成员为NULL
。 EnQueue
然后取消引用该行中的 NULL
指针
Q->rear->next = newNode;
第一次调用时。此行不是必需的,因此可以简单地删除。
还有一些其他小错误您还可以查看
createQueue
泄漏temp
。您显然不需要声明/分配这个EnQueue
缺少对 mallocnewNode
失败的错误处理。打印出“newNode Created”在这里有些误导!- 在打印指向队列尾部的指针时,使用
%p
作为格式说明符。
关于c - 使用 C 中的链表和结构实现队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14260976/