简体   繁体   中英

Queue implementation using Likedlist and structures in C

I don't understand what the problem is with this code. During compilation there are no errors, but while executing the given option of Enqueu it stops abruptly. The problem is occurring near Queue->rear->next=NULL which is correct in my view. I don't know where I'm going wrong.

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;

      }
   }
}

When the queue is empty its front and rear members are NULL . EnQueue then dereferences a NULL pointer in the line

Q->rear->next = newNode;

when it is first called. This line is not necessary so could simply be removed.

There are some other small errors you could also look at

  • createQueue leaks temp . You don't obviously need to declare/allocate this
  • EnQueue is missing error handling for failure to malloc newNode . Printing out "newNode Created" is somewhat misleading here!
  • Use %p as your format specifier when printing out a pointer to the rear of the queue.

createQueue() ,将Q->frontQ->rearNULL但在EnQueue()您正在使用Q->rear->next EnQueue() Q->rear->next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM