Double Ended Queue using Singly Linked List
A Double-Ended Queue (Deque) is a linear data structure that allows insertion and deletion of elements from both the front and rear ends.
🔍 What is a Double-Ended Queue (Deque)?
-
Pronounced “deck”
-
Supports four operations:
-
insertFront()
: Insert an element at the front -
insertRear()
: Insert an element at the rear -
deleteFront()
: Delete an element from the front -
deleteRear()
: Delete an element from the rear
-
There are two types of Deques:
-
Input-restricted Deque – insertion at only one end but deletion at both ends
-
Output-restricted Deque – deletion at only one end but insertion at both ends
✅ Basic Structure
Each node contains:
-
data
: the value -
next
: pointer to the next node
The Deque
has two pointers:
-
front
: points to the first node -
rear
: points to the last node
💡 Algorithm 1: Insert at Front
x
: Element to insert
Steps:
-
Create a new node
newNode
withdata = x
andnext = NULL
. -
If
front
isNULL
(deque is empty):-
Set
front = rear = newNode
.
-
-
Else:
-
Set
newNode->next = front
. -
Set
front = newNode
.
-
💡 Algorithm 2: Insert at Rear
Input:
-
x
: Element to insert
Steps:
-
Create a new node
newNode
withdata = x
andnext = NULL
. -
If
rear
isNULL
(deque is empty):-
Set
front = rear = newNode
.
-
-
Else:
-
Set
rear->next = newNode
. -
Set
rear = newNode
.
-
💡 Algorithm 3: Delete from Front
Steps:
-
If
front == NULL
:-
Print “Deque is empty” and return.
-
-
Store
front
in a temporary pointertemp
. -
Move
front = front->next
. -
If
front == NULL
, setrear = NULL
. -
Free
temp
.
If
front == NULL
:Print “Deque is empty” and return.
- if front==rear // only one node
- set front=rear=NULL
3.Store
front
in a temporary pointer temp
.4.Move
front = front->next
.5.Free
temp
.💡 Algorithm 4: Delete from Rear
Steps:
-
If
rear == NULL
:-
Print “Deque is empty” and return.
-
-
If
front == rear
(only one element):-
Free
front
and set bothfront = rear = NULL
. -
Return.
-
-
Else:
-
Start from
front
, traverse nodes usingtemp
untiltemp->next == rear
. -
Free
rear
. -
Set
rear = temp
andrear->next = NULL
.
-
💡 Algorithm 5: Display Deque
Steps:
-
If
front == NULL
, print “Deque is empty”. -
Else:
-
Start from
front
and traverse each node. -
Print
data
of each node.
-
Comments
Post a Comment