Implement Stack and Queue using Deque
Last Updated :
17 Apr, 2024
Deque also known as double ended queue, as name suggests is a special kind of queue in which insertions and deletions can be done at the last as well as at the beginning.
A link-list representation of deque is such that each node points to the next node as well as the previous node. So that insertion and deletions take constant time at both the beginning and the last.

Now, deque can be used to implement a stack and queue. One simply needs to understand how deque can made to work as a stack or a queue.
The functions of deque to tweak them to work as stack and queue are list below.

Examples: Stack
Input : Stack : 1 2 3
Push(4)
Output : Stack : 1 2 3 4
Input : Stack : 1 2 3
Pop()
Output : Stack : 1 2
Examples: Queue
Input: Queue : 1 2 3
Enqueue(4)
Output: Queue : 1 2 3 4
Input: Queue : 1 2 3
Dequeue()
Output: Queue : 2 3
Implementation:
Java
// Java program to implement stack and
// queue using Deque
import java.lang.*;
class GFG {
// Class for a node of deque
static class DQueNode {
int value;
DQueNode next;
DQueNode prev;
}
// Implementation of deque class
static class deque {
// Pointers to head and tail of deque
private DQueNode head;
private DQueNode tail;
// Constructor
public deque() { head = tail = null; }
// If list is empty
boolean isEmpty()
{
if (head == null)
return true;
return false;
}
// count the number of nodes in list
int size()
{
// If list is not empty
if (!isEmpty()) {
DQueNode temp = head;
int len = 0;
while (temp != null) {
len++;
temp = temp.next;
}
return len;
}
return 0;
}
// Insert at the first position
void insert_first(int element)
{
// Allocating node of DQueNode type
DQueNode temp = new DQueNode();
temp.value = element;
// If the element is first element
if (head == null) {
head = tail = temp;
temp.next = temp.prev = null;
}
else {
head.prev = temp;
temp.next = head;
temp.prev = null;
head = temp;
}
}
// Insert at last position of deque
void insert_last(int element)
{
// Allocating node of DQueNode type
DQueNode temp = new DQueNode();
temp.value = element;
// If element is the first element
if (head == null) {
head = tail = temp;
temp.next = temp.prev = null;
}
else {
tail.next = temp;
temp.next = null;
temp.prev = tail;
tail = temp;
}
}
// Remove element at the first position
public void remove_first()
{
// If list is not empty
if (!isEmpty()) {
// If there is only one node
if (head == tail) {
head = tail = null;
return;
} else {
head = head.next;
head.prev = null;
}
} else {
System.out.println("List is Empty");
}
}
// Remove element at the last position
void remove_last()
{
// If list is not empty
if (!isEmpty()) {
DQueNode temp = tail;
tail = tail.prev;
if (tail != null) {
tail.next = null;
}
return;
}
System.out.print("List is Empty");
}
// Displays the elements in deque
void display()
{
// If list is not empty
if (!isEmpty()) {
DQueNode temp = head;
while (temp != null) {
System.out.print(temp.value + " ");
temp = temp.next;
}
return;
}
System.out.print("List is Empty");
}
}
// Class to implement stack using Deque
static class Stack {
deque d = new deque();
// push to push element at top of stack
// using insert at last function of deque
public void push(int element)
{
d.insert_last(element);
}
// Returns size
public int size() { return d.size(); }
// pop to remove element at top of stack
// using remove at last function of deque
public void pop() { d.remove_last(); }
// Display
public void display() { d.display(); }
}
// Class to implement queue using deque
static class Queue {
deque d = new deque();
// enqueue to insert element at last
// using insert at last function of deque
public void enqueue(int element)
{
d.insert_last(element);
}
// dequeue to remove element from first
// using remove at first function of deque
public void dequeue() { d.remove_first(); }
// display
public void display() { d.display(); }
// size
public int size() { return d.size(); }
}
// Driver Code
public static void main(String[] args)
{
// Object of Stack
Stack stk = new Stack();
// push 7 and 8 at top of stack
stk.push(7);
stk.push(8);
System.out.print("Stack: ");
stk.display();
// For new line
System.out.println();
// pop an element
stk.pop();
System.out.print("Stack: ");
stk.display();
// For new line
System.out.println();
// Object of Queue
Queue que = new Queue();
// Insert 12 and 13 in queue
que.enqueue(12);
que.enqueue(13);
System.out.print("Queue: ");
que.display();
// New line
System.out.println();
// Delete an element from queue
que.dequeue();
System.out.print("Queue: ");
que.display();
// New line
System.out.println();
System.out.println("Size of stack is "
+ stk.size());
System.out.println("Size of queue is "
+ que.size());
}
}
// This code is contributed by sujitmeshram
// This code is modified by Susobhan Akhuli
// This code is modified by K.Harichandana
Python3
class node:
def __init__(self,val):
self.val = val
self.prev = None
self.next = None
class Deque:
def __init__(self):
self.head = self.tail = None
def isEmpty(self):
if (self.head == None): return True
return False
def insert_first(self,element):
newP = node(element)
if self.head == None:
self.head = self.tail = newP
return
newP.next = self.head
self.head.prev = newP
self.head = newP
def insert_last(self,element):
newP = node(element)
if self.head == None:
self.head = self.tail = newP
return
newP.prev = self.tail
self.tail.next = newP
self.tail = newP
def size(self):
curr = self.head
len = 0
while curr != None:
len += 1
curr = curr.next
return len
def remove_first(self):
if self.isEmpty():
print('List is Empty')
return
self.head = self.head.next
if self.head != None: self.head.prev = None
def remove_last(self):
if self.isEmpty():
print('List is Empty')
return
self.tail = self.tail.prev
if self.tail != None: self.tail.next = None
def display(self):
if self.isEmpty():
print('List is Empty')
return
curr = self.head
while curr != None:
print(curr.val,end = ' ')
curr = curr.next
print()
class Stack:
def __init__(self):
self.stack = Deque()
def push(self,element):
self.stack.insert_last(element)
def pop(self):
self.stack.remove_last()
def size(self):
return self.stack.size()
def display(self):
self.stack.display()
class Queue:
def __init__(self):
self.que = Deque()
def enqueue(self,element):
self.que.insert_last(element)
def dequeue(self):
self.que.remove_first()
def size(self):
return self.que.size()
def display(self):
self.que.display()
stk = Stack()
# push 7 and 8 at top of stack
stk.push(7)
stk.push(8)
print("Stack: ")
stk.display()
# pop an element
stk.pop()
print("Stack: ")
stk.display()
# Object of Queue
que = Queue()
# Insert 12 and 13 in queue
que.enqueue(12)
que.enqueue(13)
print("Queue: ")
que.display()
# Delete an element from queue
que.dequeue()
print("Queue: ")
que.display()
print("Size of stack is ",stk.size())
print("Size of queue is ", que.size())
C#
// C# program to implement stack and
// queue using Deque
using System;
class GFG
{
// Class for a node of deque
public
class DQueNode {
public
int value;
public
DQueNode next;
public
DQueNode prev;
}
// Implementation of deque class
public class deque {
// Pointers to head and tail of deque
private DQueNode head;
private DQueNode tail;
// Constructor
public deque() { head = tail = null; }
// If list is empty
public
bool
isEmpty()
{
if (head == null)
return true;
return false;
}
// count the number of nodes in list
public
int
size()
{
// If list is not empty
if (!isEmpty()) {
DQueNode temp = head;
int len = 0;
while (temp != null) {
len++;
temp = temp.next;
}
return len;
}
return 0;
}
// Insert at the first position
public
void
insert_first(int element)
{
// Allocating node of DQueNode type
DQueNode temp = new DQueNode();
temp.value = element;
// If the element is first element
if (head == null) {
head = tail = temp;
temp.next = temp.prev = null;
}
else {
head.prev = temp;
temp.next = head;
temp.prev = null;
head = temp;
}
}
// Insert at last position of deque
public
void
insert_last(int element)
{
// Allocating node of DQueNode type
DQueNode temp = new DQueNode();
temp.value = element;
// If element is the first element
if (head == null) {
head = tail = temp;
temp.next = temp.prev = null;
}
else {
tail.next = temp;
temp.next = null;
temp.prev = tail;
tail = temp;
}
}
// Remove element at the first position
public
void
remove_first()
{
// If list is not empty
if (!isEmpty()) {
head = head.next;
head.prev = null;
return;
}
Console.Write("List is Empty");
}
// Remove element at the last position
public
void
remove_last()
{
// If list is not empty
if (!isEmpty()) {
tail = tail.prev;
tail.next = null;
return;
}
Console.Write("List is Empty");
}
// Displays the elements in deque
public
void
display()
{
// If list is not empty
if (!isEmpty()) {
DQueNode temp = head;
while (temp != null) {
Console.Write(temp.value + " ");
temp = temp.next;
}
return;
}
Console.Write("List is Empty");
}
}
// Class to implement stack using Deque
public class Stack {
deque d = new deque();
// push to push element at top of stack
// using insert at last function of deque
public void push(int element)
{
d.insert_last(element);
}
// Returns size
public int size() { return d.size(); }
// pop to remove element at top of stack
// using remove at last function of deque
public void pop() { d.remove_last(); }
// Display
public void display() { d.display(); }
}
// Class to implement queue using deque
class Queue {
deque d = new deque();
// enqueue to insert element at last
// using insert at last function of deque
public void enqueue(int element)
{
d.insert_last(element);
}
// dequeue to remove element from first
// using remove at first function of deque
public void dequeue() { d.remove_first(); }
// display
public void display() { d.display(); }
// size
public int size() { return d.size(); }
}
// Driver Code
public static void Main(String[] args)
{
// Object of Stack
Stack stk = new Stack();
// push 7 and 8 at top of stack
stk.push(7);
stk.push(8);
Console.Write("Stack: ");
stk.display();
// For new line
Console.WriteLine();
// pop an element
stk.pop();
Console.Write("Stack: ");
stk.display();
// For new line
Console.WriteLine();
// Object of Queue
Queue que = new Queue();
// Insert 12 and 13 in queue
que.enqueue(12);
que.enqueue(13);
Console.Write("Queue: ");
que.display();
// New line
Console.WriteLine();
// Delete an element from queue
que.dequeue();
Console.Write("Queue: ");
que.display();
// New line
Console.WriteLine();
Console.WriteLine("Size of stack is " + stk.size());
Console.WriteLine("Size of queue is " + que.size());
}
}
// This code contributed by gauravrajput1
JavaScript
<script>
// Javascript program to implement stack and
// queue using Deque
// Class for a node of deque
class DQueNode
{
constructor()
{
this.value = 0;
this.next = null;
this.prev = null;
}
}
// Implementation of deque class
class deque
{
// Constructor
constructor()
{
this.head = this.tail=null;
}
// If list is empty
isEmpty()
{
if (this.head == null)
return true;
return false;
}
// count the number of nodes in list
size()
{
// If list is not empty
if (!this.isEmpty())
{
let temp = this.head;
let len = 0;
while (temp != null)
{
len++;
temp = temp.next;
}
return len;
}
return 0;
}
// Insert at the first position
insert_first(element)
{
// Allocating node of DQueNode type
let temp = new DQueNode();
temp.value = element;
// If the element is first element
if (this.head == null)
{
this.head = this.tail = temp;
temp.next = temp.prev = null;
}
else
{
this.head.prev = temp;
temp.next = this.head;
temp.prev = null;
this.head = temp;
}
}
// Insert at last position of deque
insert_last(element)
{
// Allocating node of DQueNode type
let temp = new DQueNode();
temp.value = element;
// If element is the first element
if (this.head == null)
{
this.head = this.tail = temp;
temp.next = temp.prev = null;
}
else
{
this.tail.next = temp;
temp.next = null;
temp.prev = this.tail;
this.tail = temp;
}
}
// Remove element at the first position
remove_first()
{
// If list is not empty
if (!this.isEmpty())
{
let temp = this.head;
this.head = this.head.next;
this.head.prev = null;
return;
}
document.write("List is Empty");
}
// Remove element at the last position
remove_last()
{
// If list is not empty
if (!this.isEmpty())
{
let temp = this.tail;
this.tail = this.tail.prev;
this.tail.next = null;
return;
}
document.write("List is Empty");
}
// Displays the elements in deque
display()
{
// If list is not empty
if (!this.isEmpty())
{
let temp = this.head;
while (temp != null)
{
document.write(temp.value + " ");
temp = temp.next;
}
return;
}
document.write("List is Empty");
}
}
// Class to implement stack using Deque
class Stack
{
constructor()
{
this.d= new deque();
}
// push to push element at top of stack
// using insert at last function of deque
push(element)
{
this.d.insert_last(element);
}
// Returns size
size()
{
return this.d.size();
}
// pop to remove element at top of stack
// using remove at last function of deque
pop()
{
this.d.remove_last();
}
// Display
display()
{
this.d.display();
}
}
// Class to implement queue using deque
class Queue
{
constructor()
{
this.d = new deque();
}
// enqueue to insert element at last
// using insert at last function of deque
enqueue(element)
{
this.d.insert_last(element);
}
// dequeue to remove element from first
// using remove at first function of deque
dequeue()
{
this.d.remove_first();
}
// display
display()
{
this.d.display();
}
// size
size()
{
return this.d.size();
}
}
// Driver Code
// Object of Stack
let stk = new Stack();
// push 7 and 8 at top of stack
stk.push(7);
stk.push(8);
document.write("Stack: ");
stk.display();
// For new line
document.write("<br>");
// pop an element
stk.pop();
document.write("Stack: ");
stk.display();
// For new line
document.write("<br>");
// Object of Queue
let que = new Queue();
// Insert 12 and 13 in queue
que.enqueue(12);
que.enqueue(13);
document.write("Queue: ");
que.display();
// New line
document.write("<br>");
// Delete an element from queue
que.dequeue();
document.write("Queue: ");
que.display();
// New line
document.write("<br>");
document.write("Size of stack is " +
stk.size()+"<br>");
document.write("Size of queue is " +
que.size()+"<br>");
// This code is contributed by patel2127
</script>
C++14
// C++ Program to implement stack and queue using Deque
#include <bits/stdc++.h>
using namespace std;
// structure for a node of deque
struct DQueNode {
int value;
DQueNode* next;
DQueNode* prev;
};
// Implementation of deque class
class Deque {
private:
// pointers to head and tail of deque
DQueNode* head;
DQueNode* tail;
public:
// constructor
Deque()
{
head = tail = NULL;
}
// if list is empty
bool isEmpty()
{
if (head == NULL)
return true;
return false;
}
// count the number of nodes in list
int size()
{
// if list is not empty
if (!isEmpty()) {
DQueNode* temp = head;
int len = 0;
while (temp != NULL) {
len++;
temp = temp->next;
}
return len;
}
return 0;
}
// insert at the first position
void insert_first(int element)
{
// allocating node of DQueNode type
DQueNode* temp = new DQueNode[sizeof(DQueNode)];
temp->value = element;
// if the element is first element
if (head == NULL) {
head = tail = temp;
temp->next = temp->prev = NULL;
}
else {
head->prev = temp;
temp->next = head;
temp->prev = NULL;
head = temp;
}
}
// insert at last position of deque
void insert_last(int element)
{
// allocating node of DQueNode type
DQueNode* temp = new DQueNode[sizeof(DQueNode)];
temp->value = element;
// if element is the first element
if (head == NULL) {
head = tail = temp;
temp->next = temp->prev = NULL;
}
else {
tail->next = temp;
temp->next = NULL;
temp->prev = tail;
tail = temp;
}
}
// remove element at the first position
void remove_first()
{
// if list is not empty
if (!isEmpty()) {
DQueNode* temp = head;
head = head->next;
if(head) head->prev = NULL;
delete temp;
if(head == NULL) tail = NULL;
return;
}
cout << "List is Empty" << endl;
}
// remove element at the last position
void remove_last()
{
// if list is not empty
if (!isEmpty()) {
DQueNode* temp = tail;
tail = tail->prev;
if(tail) tail->next = NULL;
delete temp;
if(tail == NULL) head = NULL;
return;
}
cout << "List is Empty" << endl;
}
// displays the elements in deque
void display()
{
// if list is not empty
if (!isEmpty()) {
DQueNode* temp = head;
while (temp != NULL) {
cout << temp->value << " ";
temp = temp->next;
}
cout << endl;
return;
}
cout << "List is Empty" << endl;
}
};
// Class to implement stack using Deque
class Stack : public Deque {
public:
// push to push element at top of stack
// using insert at last function of deque
void push(int element)
{
insert_last(element);
}
// pop to remove element at top of stack
// using remove at last function of deque
void pop()
{
remove_last();
}
};
// class to implement queue using deque
class Queue : public Deque {
public:
// enqueue to insert element at last
// using insert at last function of deque
void enqueue(int element)
{
insert_last(element);
}
// dequeue to remove element from first
// using remove at first function of deque
void dequeue()
{
remove_first();
}
};
// Driver Code
int main()
{
// object of Stack
Stack stk;
// push 7 and 8 at top of stack
stk.push(7);
stk.push(8);
cout << "Stack: ";
stk.display();
// pop an element
stk.pop();
cout << "Stack: ";
stk.display();
// object of Queue
Queue que;
// insert 12 and 13 in queue
que.enqueue(12);
que.enqueue(13);
cout << "Queue: ";
que.display();
// delete an element from queue
que.dequeue();
cout << "Queue: ";
que.display();
cout << "Size of Stack is " << stk.size() << endl;
cout << "Size of Queue is " << que.size() << endl;
return 0;
}
OutputStack: 7 8
Stack: 7
Queue: 12 13
Queue: 13
Size of Stack is 1
Size of Queue is 1
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem