Updated:13/01/2024 by Computer Hope
Go BackIn this tutorial, you will learn what a double ended queue using linked List is. Also, you will find implementation of double ended queue using linked List in C, C++, Java and Python.
#include<stdio.h>
#include<conio.h>
struct queue
{ int no;
struct queue *next;
};
struct queue *front=NULL,*rear=NULL;
void insertrear(int val)
{
struct queue *q;
q=(struct queue *)malloc(sizeof(struct queue));
q->no=val;
q->next=NULL;
if(front==NULL)
{ front=rear=q;
return;
}
rear->next=q;
rear=q;
}
void insertfront(int val)
{
struct queue *q;
q=(struct queue *)malloc(sizeof(struct queue));
q->no=val;
q->next=front;
if(front==NULL)
{
front=rear=q;
return;
}
front=q;
}
int deletefront()
{int val;
struct queue *q;
if(front==NULL)
{ printf("\nQueue is Empty");
return -999;
}
q=front;
val=front->no;
if(front==rear)
front=rear=NULL;
else
front=front->next;
free(q);
return val;
}
int deleterear()
{ int val;
struct queue *q=front ;
if(front==NULL)
{ printf("\nQueue is Empty");
return -999;
}
val=rear->no;
if(front==rear)
front=rear=NULL;
else
{ while(q->next->next!=NULL)
q=q->next;
rear=q;
q=q->next;
rear->next=NULL; }
free(q);
return val;
}
void show()
{
struct queue *q=front;
if(front==NULL)
{ printf("\nQueue is Empty");
return; }
q=front;
while(q!=NULL)
{ printf("%d\t",q->no);
q=q->next;
}
}
void main()
{ int ch,n;
do
{
printf("\n1. Insert in Front");
printf("\n2. Insert in Rear");
printf("\n3. Delete from Front");
printf("\n4. Delete from Rear");
printf("\n5. Show");
printf("\n0. Exit");
printf("\n\nEnter Your Choice");
scanf("%d",&ch);
switch(ch)
{ case 1:printf("\nEnter Number ");
scanf("%d",&n);
insertfront(n);
break;
case 2:printf("\nEnter Number ");
scanf("%d",&n);
insertrear(n);
break;
case 3 :n=deletefront();
if(n!=-999)
printf("\n%d deleted",n);
break;
case 4: n=deleterear();
if(n!=-999)
printf("\n%d deleted",n);
break;
case 5 : show( );
break;
case 0:break;
default:printf("\nWrong Choice");
}
} while( ch != 0 ) ;
}
We learn abstract data structure akin to stacks is called a queue. A queue is open at both ends, in contrast to stacks. Data is always inserted (enqueued) using one end and removed (dequeued) using the other. The data item that is saved first will be accessed first in a queue that uses the First-In-First-Out technique. But in , Doubly Linked List implementation can be the preferred choice for Deque when the input data is dynamic and expected to grow larger. So, the Deque grows and shrinks based on the input data. However, the linked list implementation is slower than Array and requires additional memory.