The Wayback Machine - https://web.archive.org/web/20240819104116/https://www.geeksforgeeks.org/implement-dynamic-deque-using-templates-class-and-a-circular-array/
Open In App

Implement dynamic deque using templates class and a circular array

Last Updated : 21 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The task is to implement a dynamic Deque using templates class and a circular array, having the following functionalities:  

  • front(): Get the front item from the deque.
  • back(): Get the last item from the deque.
  • push_back(X): Push X at the end of the deque.
  • push_front(X): Push X at the start of the deque.
  • pop_front(): Delete an element from the start of the deque.
  • pop_back(): Delete an element from the end of the deque
  • empty(): Checks whether deque is empty or not
  • capacity(): Current maximum number of elements deque can store
  • size(): Number of elements in the deque

Below is the step by step illustration:

  • Initially, the deque is empty

  • Insert 1 to the back of deque

  • Insert elements 2, 3 to the back of deque

  • Insert 4 to the front of deque

  • Insert 5 to the back of deque

  • Pop 2 elements from front and 2 elements from the back of deque

  • Pop 1 element from the front of deque

Approach: The idea is to double the size of the array used every time the capacity of the array gets full and copy the elements of the previous array into the new array. Follow the steps below to solve the problem:

  • Initialize 4 variables say frontIndex, backIndex, sizeVar, and capacityVar, and an array say arr[] to implement the deque.
  • Define a function say capacity() to find the size of the current array used and return the value of the variable, capacityVar.
  • Define a function say size() to find the count of elements in the deque and return the value of the variable, sizeVar.
  • Define a function say full() to find if the deque is full or not and return true if sizeVar is equal to capacityVar. Otherwise, return false.
  • Define a function say empty() to find if the deque is empty or not and return true if frontIndex and backIndex are equal to -1. Otherwise, return false.
  • Define a function say Front() to print the front element of the deque. If deque is not empty(), print the element of arr[frontIndex].
  • Define a function say Back() to print the last element of the deque. If deque is not empty(), print the element of arr[BackIndex].
  • Define a function say push_back(X) to insert an element at the end of the deque:
    • If the deque is full, then double the size of the current array and copy the elements of the previous array into the new array.
    • If deque is empty(), then assign frontIndex = backIndex = 0 and then assign X to both arr[frontIndex] and arr[backIndex] and then increment sizeVar by one.
    • Else, update backIndex as backIndex = (backIndex+1) %capacityVar and then assign X to arr[backIndex] and increment sizeVar by one.
  • Define a function say push_front(X) to insert an element at the start of the deque:
    • If the deque is full, then double the size of the current array and copy the elements of the previous array into the new array.
    • If deque is empty(), then assign frontIndex = backIndex = 0 and then assign X to both arr[frontIndex] and arr[backIndex] and then increment sizeVar by one.
    • Else, update frontIndex as frontIndex = (frontIndex-1 + capacityVar)%capacityVar and then assign X to arr[frontIndex] and increment sizeVar by one.
  • Define a function say pop_front() to delete an element at the front of the deque:
    • If the deque is empty, print “Underflow”.
    • Else if sizeVar is equal to 1 then assign -1 to frontIndex and backIndex both and then decrement sizeVar by one.
    • Else, Update frontIndex as frontIndex = (frontIndex+1)%capacityVar and decrement sizeVar by one.
  • Define a function say pop_back() to delete an element at the front of the deque:
    • If the deque is empty, print “Underflow”.
    • Else if sizeVar is equal to 1 then assign -1 to frontIndex and backIndex both and then decrement sizeVar by one.
    • Else, Update backIndex as backIndex = (backndex-1 + capacityVar) %capacityVar and decrement sizeVar by one.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Class definition of the deque
template <class X>
class Deque {
 
private:
    // Stores the frontIndex
    int frontIndex;
 
    // Stores the backIndex
    int backIndex;
 
    // Stores the array
    X* arr;
 
    // Stores the size of deque
    int sizeVar;
 
    // Stores the size of array
    int capacityVar = 4;
 
public:
    // Deque class constructor
    Deque()
    {
        arr = new X[capacityVar];
        frontIndex = backIndex = -1;
        sizeVar = 0;
    }
 
    // Function methods
    bool empty();
    bool full();
    void push_back(X x);
    void push_front(X x);
    void pop_front();
    void pop_back();
    X front();
    X back();
    int capacity();
    int size();
};
 
// Function to find the capacity of the deque
template <class X>
int Deque<X>::capacity()
{
    return capacityVar;
}
 
// Function to find the number of elements
// present in deque
template <class X>
int Deque<X>::size() { return sizeVar; }
 
// Function to check if deque is empty or not
template <class X>
bool Deque<X>::empty()
{
    if (frontIndex == -1 && backIndex == -1)
        return true;
    else
        return false;
}
 
// Function to check if deque is full or not
template <class X>
bool Deque<X>::full()
{
    if (sizeVar == capacityVar)
        return true;
    else
        return false;
}
 
// Function to find the front element of the deque
template <class X>
X Deque<X>::front()
{
    // If deque is empty
    if (empty()) {
        cout << "Deque underflow" << endl;
        abort();
    }
    return arr[frontIndex];
}
 
// Function to find the last element of the deque
template <class X>
X Deque<X>::back()
{
    // If deque is empty
    if (empty()) {
        cout << "Deque underflow" << endl;
        abort();
    }
    return arr[backIndex];
}
 
// Function to insert the element
// to the back of the deque
template <class X>
void Deque<X>::push_back(X x)
{
    if (full()) {
 
        // If the deque is full, then
        // double the capacity
        capacityVar = capacityVar * 2;
 
        // Initialize new array of
        // double size
        X* temp = new X[capacityVar];
 
        // Copy the elements of the
        // previous array
        int i = frontIndex;
        int j = 0;
        while (i != backIndex) {
            temp[j] = arr[i];
            i = (i + 1) % sizeVar;
            j++;
        }
        temp[j] = arr[i];
 
        frontIndex = 0;
        backIndex = sizeVar - 1;
 
        // Deallocate the memory
        // of previous array
        delete[] arr;
        arr = temp;
    }
 
    // If size is zero
    if (empty()) {
        frontIndex = backIndex = 0;
        arr[backIndex] = x;
        sizeVar++;
        return;
    }
 
    // Increment back index cyclically
    backIndex = (backIndex + 1) % capacityVar;
    arr[backIndex] = x;
    sizeVar++;
    return;
}
 
// Function to insert the element
// to the front of the deque
template <class X>
void Deque<X>::push_front(X x)
{
    if (full()) {
 
        // If the deque is full, then
        // double the capacity
        capacityVar = capacityVar * 2;
 
        // Initialize new array of
        // double size
        X* temp = new X[capacityVar];
 
        // Copy the elements of the
        // previous array
        int i = frontIndex;
        int j = 0;
        while (i != backIndex) {
            temp[j] = arr[i];
            i = (i + 1) % sizeVar;
            j++;
        }
        temp[j] = arr[i];
 
        frontIndex = 0;
        backIndex = sizeVar - 1;
 
        // Deallocate the memory
        // of previous array
        delete[] arr;
        arr = temp;
    }
 
    // If size is zero
    if (empty()) {
        frontIndex = backIndex = 0;
        arr[backIndex] = x;
        sizeVar++;
        return;
    }
 
    // Decrement front index cyclically
    frontIndex
        = (frontIndex - 1 + capacityVar) % capacityVar;
    arr[frontIndex] = x;
    sizeVar++;
    return;
}
 
// Function to delete the element
// from the front of the deque
template <class X>
void Deque<X>::pop_front()
{
    // If deque is empty
    if (empty()) {
        cout << "Deque underflow" << endl;
        abort();
    }
 
    // If there is only one character
    if (frontIndex == backIndex) {
 
        // Mark deque as empty
        // and decrement sizeVar
        frontIndex = backIndex = -1;
        sizeVar--;
        return;
    }
 
    // Increment frontIndex cyclically
    frontIndex = (frontIndex + 1) % capacityVar;
    sizeVar--;
    return;
}
 
// Function to delete the element
// from the back of the deque
template <class X>
void Deque<X>::pop_back()
{
    // If deque is empty
    if (empty()) {
        cout << "Deque underflow" << endl;
        abort();
    }
 
    // If there is only one character
    if (frontIndex == backIndex) {
 
        // Mark deque as empty
        // and decrement sizeVar
        frontIndex = backIndex = -1;
        sizeVar--;
        return;
    }
 
    // Decrement backIndex cyclically
    backIndex = (backIndex - 1 + capacityVar) % capacityVar;
    sizeVar--;
    return;
}
 
// Driver Code
int main()
{
    // Deque initialization
    Deque<int> q;
 
    // Iterate range [1, 100],
    // push even numbers at the back
    // and push odd numbers at the front
    for (int i = 1; i < 10; i++)
        if (i % 2 == 0)
            q.push_back(i);
        else
            q.push_front(i);
 
    // Print the current capacity
    cout << "Current capacity " << q.capacity() << endl;
 
    // Print the current size
    cout << "Current size " << q.size() << endl;
 
    // Print front elements of deque
    cout << "Front element " << q.front() << endl;
 
    // Print last element of the deque
    cout << "Rear element " << q.back() << endl;
 
    cout << endl;
 
    cout << "Pop an element from front" << endl;
 
    // Pop an element from the front of deque
    q.pop_front();
 
    cout << "Pop an element from back" << endl;
 
    // Pop an element from the back of deque
    q.pop_back();
 
    cout << endl;
 
    // Print the current capacity
    cout << "Current capacity " << q.capacity() << endl;
 
    // Print current size
    cout << "Current size " << q.size() << endl;
 
    // Print front elements of deque
    cout << "Front element " << q.front() << endl;
 
    // Print last element of the deque
    cout << "Rear element " << q.back() << endl;
 
    return 0;
}


 
 

Output

Current capacity 16
Current size 9
Front element 9
Rear element 8

Pop an element from front
Pop an element from back

Current capacity 16
Current size 7
Front element 7
Rear element 6

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Similar Reads

Implement dynamic queue using templates class and a circular array
In this article, we will discuss how to create a dynamic circular queue using a circular array having the following functionality: Front(): Get the front item from the queue.Back(): Get the last item from the queue.Push(X): Push the X in the queue at the end of the queue.Pop(): Delete an element from the queue. Below is the step-by-step illustratio
7 min read
deque::at() and deque::swap() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::at()at() function is us
4 min read
deque::pop_front() and deque::pop_back() in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::pop_front() pop_front()
4 min read
deque::clear() and deque::erase() in C++ STL
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::clear() The clear()
5 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
deque::begin() and deque::end in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::begin()begin() function
3 min read
deque::emplace_front() and deque::emplace_back() in C++ STL
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::emplace_front()This fun
5 min read
Difference Between deque::cbegin and deque::assign in C++
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. Here we will see the differenc
3 min read
Difference Between deque::assign and deque::at in C++
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. Here we will see the differenc
3 min read
Difference Between deque::assign and deque::back in C++
Deque or Double-ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. Deque::assign deque::assign is
3 min read
Difference Between deque::begin and deque::assign in C++
Deque or Double-ended queue are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in the case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. Here we will see the difference
3 min read
Difference between Queue and Deque (Queue vs. Deque)
Queue: The queue is an abstract data type or linear data structure from which elements can be inserted at the rear(back) of the queue and elements can be deleted from the front(head) of the queue. The operations allowed in the queue are:insert an element at the reardelete element from the frontget the last elementget the first elementcheck the size
3 min read
Deque::front() and deque::back() in C++ STL
Deque or Double Ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed in the deque. deque::front()fron
4 min read
Deque::empty() and deque::size() in C++ STL
Deque or Double Ended queues are sequence containers with the feature of expansion and contraction on both ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also at the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed in the deque. deque::empty() emp
4 min read
Implementation of Deque using circular array
Implement a deque Using a circular array: Deque or Double Ended Queue is a generalized version of the Queue data structure that allows insert and delete at both ends Operations on Deque: Mainly the following four basic operations are performed on queue: insertFront(): Adds an item at the front of Deque.insertRear(): Adds an item at the rear of Dequ
15+ min read
Implement Stack and Queue using Deque
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 beg
15 min read
Circular Subsequence Shift with Deque
Given a string S of lowercase English letters, each character is linked to one of T's unique identifiers. Specifically, character positions are associated with identifiers from 1 to T. For each identifier IDi (ranging from 1 to M), perform a clockwise/right circular shift by 1 on the portion of string S linked to identifier IDi. This operation repl
10 min read
How to implement our own Dynamic Array class in Java?
Given task is to implement a class in Java which behaves just like the Dynamic array using ArrayList. ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. ArrayList elements are placed in contiguous storage so that
4 min read
Implement Dynamic Multi Stack (K stacks) using only one Data Structure
In this article, we will see how to create a data structure that can handle multiple stacks with growable size. The data structure needs to handle three operations: push(x, stackNum) = pushes value x to the stack numbered stackNumpop(stackNum) = pop the top element from the stack numbered stackNumtop(stackNum) = shows the topmost element of the sta
15+ min read
What is Circular Queue | Circular Queue meaning
A circular queue is an extended version of regular queue in which the last element of the queue is connected to the first element of the queue forming a cycle. Properties of Circular Queue: Along with the properties of a regular queue the circular queue has som other unique properties as mentioned below: Front and rear pointers: Two pointers, one a
4 min read
Circular Linked List Implementation of Circular Queue
Prerequisite – Circular Singly Linked List We have discussed basics and how to implement circular queue using array in set 1. Circular Queue | Set 1 (Introduction and Array Implementation) In this post another method of circular queue implementation is discussed, using Circular Singly Linked List. Operations on Circular Queue: Front:Get the front i
9 min read
Implementing Stack Using Class Templates in C++
The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. 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). The simple idea is to pa
5 min read
Segregate even and odd nodes in a Linked List using Deque
Given a Linked List of integers. The task is to write a program to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. It is not needed to keep the order of even and odd nodes the same as that of the original list, the task is just to rearrange the nodes such that all even valued nodes ap
10 min read
Implementation of Deque using doubly linked list
Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. In previous post Implementation of Deque using circular array has been discussed. Now in this post we see how we implement Deque using Doubly Linked List. Operations on Deque :Mainly the following four basic operations are perfor
15+ min read
Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
13 min read
Python3 Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Javascript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Deque | Set 1 (Introduction and Applications)
Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. Operations on Deque: Below is a table showing some basic operations along with their time complexity, performed on deques. Operation Description Time Complexitypush_front() Inserts the element at the beginning. O(1) push_back() A
5 min read
Difference between Queue and Deque in C++
Queue: A Queue is a linear data structure that follows a First In First Out (FIFO) order in which the operations are performed. It is a type of container adaptor where elements are inserted into one end of the container and deleted from the other. Functions: empty(): Tests whether the queue is empty.size(): Returns the unsigned int, size of the que
4 min read
Applications, Advantages and Disadvantages of Deque
Deque is a type of queue in which insert and deletion can be performed from either front or rear. It does not follow the FIFO rule. It is also known as double-ended queue Operations on Deque: Deque consists of mainly the following operations: Insert FrontInsert RearDelete FrontDelete Rear 1. Insert at the Front: This operation is used to add an ele
4 min read
three90RightbarBannerImg