I'm trying to implement queue using linked lists. Here is my program
#include <stdio.h>
#include <stdlib.h>
struct queue_struct{
int ele;
struct queue_struct *next;
};
struct Queue{
struct queue_struct *front, *rear;
};
int isEmpty(struct Queue *q){
return (q->front==NULL||q->rear==NULL);
}
void enqueue(struct Queue *q, int x){
struct queue_struct *temp=(struct queue_struct *)malloc(sizeof(struct queue_struct));
temp->ele=x;
temp->next=NULL;
if(isEmpty(q)){
q->front=q->rear=temp;
return;
}
q->rear=temp;
printf("The item %d has been enqueued into the queue\n", x);
}
void dequeue(struct Queue *q){
if(isEmpty(q)){
printf("The queue is already empty. No more elements can be removed!\n");
return;
}
struct queue_struct *temp=q->front;
printf("The item %d has been dequeued from the queue\n", temp->ele);
q->front=q->front->next;
if(q->front=NULL)
q->rear=NULL;
free(temp);
}
void display(struct Queue *q){
struct queue_struct *temp=q->front;
int len;
printf("The contents of the queue are:\n");
if(isEmpty(q)){
printf("Nothing to be shown, the queue is empty.\n");
return;
}
while(temp!=NULL){
temp=temp->next;
len++;
}
temp=q->front;
for(int i=1;i<len-1;i++){
printf("| %d |\n", temp->ele);
printf(" ------ \n");
temp=temp->next;
}
printf("| %d |\n", temp->ele);
}
int main()
{
int choice, element;
printf("LET'S START WITH AN EMPTY QUEUE\n\n");
struct Queue *q=(struct Queue *)malloc(sizeof(struct Queue));
q->front=q->rear=NULL;
while(1){
printf("\nMENU\n");
printf("----\n");
printf("\t1. Enqueue\n");
printf("\t2. Dequeue\n");
printf("\t3. Display queue\n");
printf("\t4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice){
case 1: printf("Enter the element to be enqueued: ");
scanf("%d", &element);
enqueue(q, element);
break;
case 2: dequeue(q);
break;
case 3: display(q);
break;
case 4: printf("Program terminated successfully!\n");
return 0;
default: printf("Invalid input");
}
}
}
However, when I'm trying to enqueue an element, I'm getting a segmentation fault
Upon debugging I find that my isEmpty() function is the culprit, but I can't seem to find the problem. Considering the nature of the problem, I thought the front OR rear should be NULL for the queue to be empty. Am I wrong in my understanding? Any help is appreciated.
Edit
As suggested by @interjay, I have made changes to the q=NULL
part of the main()
method. However, my display
method is now going awry. I don't understand why.