I was trying a C program on queue as a linked list. Whenever I try to execute, it crashes whenever it encounters if condition comparing a pointer (q->front in this case) with NULL. Please check the following code:
struct node
{
int info;
node *next;
};
struct que
{
struct node *front
struct node *rear;
que() { front = rear = NULL; }
};
struct que *pq;
/* prototypes */
void Displace(struct que *q);
int Empty(struct que *q);
void Insert(struct que *q,int x);
void Delete(struct que *q);
int main()
{
int cho;
while(1)
{
printf("Enter 1 to insert in a queue\n");
printf("Enter 2 to delete in a queue\n");
printf("Enter 3 to display the queue\n");
scanf("%d", &cho);
if (cho == 1)
{
int x;
printf("Enter the info to be added\n");
scanf("%d",&x);
Insert(pq, x);
}
else if (cho == 2)
Delete(pq);
else if (cho == 3)
Displace(pq);
}
return 0;
}
int Empty(struct que *q)
{
return ((q-> front == NULL) ? 1 : 0); //Error
}
void Insert(struct que *q, int a)
{
node *p;
p = new node;
p->info = a;
p->next = NULL;
if ((q->r) == NULL) //Error. I get crash and this statement is never executed.
(q->f) = p;
else (q->r)->next = p;
(q->r) = p;
printf("Node added\n");
}
void Delete(struct que *q)
{
node *p = NULL;
if (Empty(q))
{
printf("Empty queue.Insert some elements\n");
return;
}
p = q->front;
q->front = p->next;
delete p;
printf("Node deleted\n");
}
void Displace(struct que *q)
{
if (Empty(q))
{
printf("Empty queue.Insert some elements\n");
return;
}
node *i = NULL;
for (i = q->front; i != NULL; i = i->next)
printf("%d\n", i->info);
}
I suspect there's something wrong with the statement if ((q->rear) == NULL). Executing the program results in a crash " has stopped working". I have also tried replacing it with if (!q->rear) , but without much success. I am unable to find a problem in my code.Please help me..Thanks
using namespace std;makes this a C++ program.