Queue using linked list
What is a Queue?
-
A Queue is a linear data structure that follows FIFO (First In First Out) principle.
-
Insertion happens at the rear (end).
-
Deletion happens at the front (beginning).
Think of a queue like a line of people at a ticket counter:
First person enters first, leaves first.
How to Implement Queue using Linked List?
-
Use a linked list instead of an array.
-
Maintain two pointers:
-
front
: Points to the first element. -
rear
: Points to the last element.
-
-
Each node contains:
-
Data
-
Pointer to next node
Algorithms for Queue using Linked List
Enqueue (Insert at the end)
1. Create a new node and assign value to its data field.
2. Set new node's next pointer to NULL.
3. If front == NULL (Queue is empty):
a. Set front = new node
b. Set rear = new node
4. Else:
a. Set rear->next = new node
b. Set rear = new node
5. End
Dequeue (Remove from Front)
Algorithm Dequeue():
1. If front == NULL:
a. Queue is empty. (Underflow condition)
b. Return error or -1
2. Else:
a. Save front node temporarily (temp = front)
b. Store temp->data to return later
c. Move front to front->next
d. If front == NULL after moving:
i. Set rear = NULL (Queue became empty)
e. Free the temporary node (temp)
f. Return the stored data
3. End
3. Display Queue
1. If front == NULL:
a. Print "Queue is empty"
2. Else:
a. Start from temp = front
b. While temp is not NULL:
i. Print temp->data
ii. Move temp to temp->next
3. End
#include<conio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
}*front=NULL,*rear=NULL;
void enqueue()
{
struct Node *newnode=(struct Node*)malloc(sizeof(struct Node));
printf("Enter data:");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(front==NULL)
{
front=newnode;
rear=newnode;
}
else
{
rear->next=newnode;
rear=newnode;
}
}
int dequeue()
{
if (front==NULL)
{printf("Queue is empty...underflow");return -1;}
else
{
struct Node *temp;
temp=front;
int rv=front->data;
front=front->next;
if(front==NULL) rear=NULL;
free(temp);
return(rv);
}
}
void displayQ()
{
struct Node *temp=front;
while(temp!=NULL)
{
printf(" %d---->",temp->data);
temp=temp->next;
}
printf(" NULL");
}
void main()
{
int ch;
do
{
printf("\nMenu\n----\n1.Enqueue\n2.Dequeue\n3.Display\n4.Exit");
printf("\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
enqueue();
displayQ();
break;
case 2:
int data;
data=dequeue();
if(data!=-1)
printf("The dequed data is:%d\n",data);
displayQ();
break;
case 3:
displayQ();
break;
case 4:
exit(0);
default:
printf("There is no such operation:");
}
}
while(1);
}
Comments
Post a Comment