在C中使用Likedlist和结构实现队列

在C中使用Likedlist和结构实现队列,c,linked-list,queue,structure,C,Linked List,Queue,Structure,我不明白这个代码有什么问题。编译期间没有错误,但在执行给定的Enqueu选项时,它会突然停止。问题发生在队列->后方->下一步=NULL附近,在我看来这是正确的。我不知道我错在哪里 struct ListNode { int data; struct ListNode *next; }; struct Queue { struct ListNode *front; struct ListNode *rear; }; struct Queue

我不明白这个代码有什么问题。编译期间没有错误,但在执行给定的Enqueu选项时,它会突然停止。问题发生在队列->后方->下一步=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;

      }
   }
}

当队列为空时,其
前部
后部
成员为
NULL
EnQueue
然后取消对行中
NULL
指针的引用

Q->rear->next = newNode;
当它第一次被调用时。该行不是必需的,因此可以简单地删除

您还可以查看其他一些小错误

  • createQueue
    leaks
    temp
    。您显然不需要声明/分配此
  • EnQueue
    缺少对malloc
    newNode
    失败的错误处理。打印出“newNode Created”在这里有些误导
  • 打印指向队列后部的指针时,请使用
    %p
    作为格式说明符

createQueue()
中,您将
Q->front
Q->rear
设置为
NULL
,但在
EnQueue()
中,您正在使用
Q->rear->next
createQueue
中,您正在泄漏
temp=malloc(sizeof(struct ListNode))。如果您在编译时启用了警告,例如,
gcc-Wall
,您将看到有很多(严重的)警告需要修复。另外,
Dequeue
丢失,因此这显然不是实际代码。