Algorithm:
- Define a struct for each node in the queue. Each node in the queue
contains data and link to the next node. Front and rear pointer points to first and
last node inserted in the queue. - The operations on the queue are
a. INSERT data into the queue
b. DELETE data out of queue - INSERT DATA INTO queue
a. Enter the data to be inserted into queue.
b. If TOP is NULL
i. The input data is the first node in queue. ii.
The link of the node is NULL.
iii. TOP points to that node. c. If
TOP is NOT NULL
i. The link of TOP points to the new node. ii.
TOP points to that node.
- DELETE DATA FROM queue a. If
TOP is NULL
i. the queue is empty b. If
TOP is NOT NULL
i. The link of TOP is the current TOP.
ii. The pervious TOP is popped from queue. - The queue represented by linked list is traversed to display its content.
Program:
#include<stdio.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
}*front = NULL, *rear = NULL;
void insert();
void delet();
void display();
int item;
void main()
{
int ch;
do
{
printf("\n\n1.\tEnqueue\n2.\tDequeue\n3.\tDisplay\n4.\tExit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
delet();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("\n\nInvalid choice. Please try again...\n");
}
} while(1);
}
void insert()
{
printf("\n\nEnter ITEM: ");
scanf("%d", &item);
if(rear == NULL)
{
rear = (struct node *)malloc(sizeof(struct node));
rear->info = item;
rear->link = NULL;
front = rear;
}
else{
rear->link = (struct node *)malloc(sizeof(struct node));
rear = rear->link;
rear->info = item;
rear->link = NULL;
}}
void delet(){
struct node *ptr;
if(front == NULL)
printf("\n\nQueue is empty.\n");
else{
ptr = front;
item = front->info;
front = front->link;
free(ptr);
printf("\nItem deleted: %d\n", item);
if(front == NULL)
rear = NULL;
}}
void display()
{
struct node *ptr = front;
if(rear == NULL)
printf("\n\nQueue is empty.\n");
else
{
printf("\n\n");
while(ptr != NULL)
{
printf("%d\t",ptr->info);
ptr = ptr->link;
getch();
}}}