Open In App

Implementation of Deque using doubly linked list

Last Updated : 12 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
23 Likes
Like
Report

A Deque (Double-Ended Queue) is a data structure that allows adding and removing elements from both the front and rear ends. Using a doubly linked list to implement a deque makes these operations very efficient, as each node in the list has pointers to both the previous and next nodes. This means we can insert and delete elements from both ends in constant time.

Operations on Deque

The following four basic operations are typically performed on a deque:

  • insertFront(): Adds an item at the front of the deque.
  • insertRear(): Adds an item at the rear of the deque.
  • deleteFront(): Removes an item from the front of the deque.
  • deleteRear(): Removes an item from the rear of the deque.

Additionally, the following operations are also supported:

  • getFront(): Retrieves the front item from the deque.
  • getRear(): Retrieves the last item from the deque.
  • isEmpty(): Checks if the deque is empty.
  • size(): Returns the number of elements in the deque.
  • erase(): Removes all elements from the deque.
deque-using-ll
Deque using Linked List

Doubly Linked List Representation of Deque

For implementing deque, we need to keep track of two pointers, front and rear. We enqueue (push) an item at the rear or the front end of deque and dequeue(pop) an item from both rear and front end.

Working

Declare two pointers front and rear of type Node, where Node represents the structure of a node of a doubly linked list. Initialize both of them with value NULL.

Insertion at Front end

1. Allocate space for a newNode of doubly linked list.
2. IF newNode == NULL, then
3. print "Overflow"
4. ELSE
5. IF front == NULL, then
6. rear = front = newNode
7. ELSE
8. newNode->next = front
9. front->prev = newNode
10. front = newNode

Insertion at Rear end

1. Allocate space for a newNode of doubly linked list.
2. IF newNode == NULL, then
3. print "Overflow"
4. ELSE
5. IF rear == NULL, then
6. front = rear = newNode
7. ELSE
8. newNode->prev = rear
9. rear->next = newNode
10. rear = newNode

Deletion from Front end

1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initialize temp = front
5. front = front->next
6. IF front == NULL
7. rear = NULL
8. ELSE
9. front->prev = NULL
10 Deallocate space for temp

Deletion from Rear end

1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initialize temp = rear
5. rear = rear->prev
6. IF rear == NULL
7. front = NULL
8. ELSE
9. rear->next = NULL
10 Deallocate space for temp

C++
C Java Python C# JavaScript

Output
Rear: 10
New Rear: 5
Front: 15
Size: 2
New Front: 5
  • Time Complexity : Time complexity of operations like insertFront(), insertRear(), deleteFront(), deleteRear() is O(1). The Time Complexity of erase() is O(n).
  • Auxiliary space: O(1)

Next Article
Article Tags :
Practice Tags :

Similar Reads