Program 2 : Dynamic implementation of linear queue using pointers
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct queue
{
int info;
struct queue *link;
}*front,*rear;
void initialize();
void lqinsert();
void lqdelete();
void lqtraverse();
void main()
{
int choice;
initialize();
while(1)
{
clrscr();
printf("\nDYNAMIC IMPLEMENTATION OF LINEAR QUEUE");
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Traverse");
printf("\n4. Exit");
printf("\n\nEnter your choice [1/2/3/4] : ");
scanf("%d",&choice);
switch(choice)
{
case 1: lqinsert();
break;
case 2: lqdelete();
break;
case 3: lqtraverse();
break;
case 4: exit(0);;
default : printf("\nInvalid choice");
}
getch();
}
}
// Function for initialize linear Queue
void initialize()
{
front=rear=NULL;
}
// Function to insert element in Linear queue
void lqinsert()
{
struct queue *ptr;
int num;
ptr=(struct queue*)malloc(sizeof(struct queue));
printf("\nEnter element to be inserted in queue : ");
scanf("%d",&num);
ptr->info=num;
ptr->link=NULL;
if(front==NULL)
{
front=ptr;
rear=ptr;
}
else
{
rear->link=ptr;
rear=ptr;
}
}
// Function to delete element from Linear queue
void lqdelete()
{
if(front==NULL)
{
printf("\nQueue is empty (Queue underflow)");
return;
}
struct queue *ptr;
int num;
ptr=front;
num=ptr->info;
printf("\nThe deleted element is : %d",num);;
front=front->link;
if(front==NULL)
rear=NULL;
free(ptr);
}
// Function to display Linear Queue
void lqtraverse()
{
struct queue *ptr;
if(front==NULL)
{
printf("\nQueue is empty (Queue underflow)");
return;
}
else
{
ptr=front;
printf("\n\nQueue elements are : \n");
printf("\nROOT");
while(ptr!=NULL)
{
printf(" -> %d",ptr->info);
ptr=ptr->link;
}
printf(" -> NULL");
}
}
CIRCULAR QUEUES
The queue that we implemented using an array suffers from one limitation. In that
implementation there is a possibility that the queue is reported as full (since rear has
reached the end of the array), even though in actuality there might be empty slots at the
beginning of the queue. To overcome this limitation we can implement the queue as a
circular queue. Here as we go on adding elements to the queue and reach the end of the
array, the next element is stored in the first slot the array (provided it is free). Suppose an
array arr of n elements is used to implement a circular queue we may reach arr[n-1]. We