Back to Data Structures & Algorithms
2026-03-257 min read

Deque Implementation in Python, Java, C, and C++

Learn Deque Implementation in Python, Java, C, and C++ step by step with clear examples and exercises.

Title: Deque Implementation in Python, Java, C, and C++ - A full guide

Why This Matters

Understanding deque implementation is crucial for efficient data manipulation in computer programming. The double-ended queue (deque) allows insertion and deletion of elements from both ends, making it an essential tool for solving real-world problems, preparing for interviews, and debugging common errors that may arise during coding.

This guide will provide a detailed explanation of deque implementation in Python, Java, C, and C++, including examples, worked exercises, and common mistakes to avoid.

Prerequisites

To fully grasp this lesson, you should have a good understanding of the following concepts:

  1. Basic programming concepts (variables, loops, functions)
  2. Data structures (arrays, linked lists, stacks, and queues)
  3. Object-oriented programming principles (for Java and C++)
  4. Python syntax and standard library knowledge
  5. Familiarity with dynamic memory allocation in C/C++
  6. Understanding of big O notation for time complexity analysis

Core Concept

Definition and Uses of Deque

A deque is a double-ended queue that allows elements to be added or removed from either end (front or rear). This makes it particularly useful in scenarios where frequent insertions and deletions are required at both ends, such as network packet processing, web browser history, undo/redo operations, and priority queues.

Deque Implementation in Python

Python provides a built-in deque data structure in the collections module:

from collections import deque

Creating an empty deque

my_deque = deque()

Adding elements to the deque

my_deque.append(1)

my_deque.appendleft(0)

Removing elements from the deque

my_deque.pop() # removes from rear

my_deque.popleft() # removes from front


#### Advantages of Python's built-in deque:

- Constant time complexity for append(), appendleft(), popleft(), and pop() operations (O(1))
- Efficient implementation using linked lists

### Deque Implementation in Java

In Java, we can implement a deque using an `ArrayList` or a custom linked list:

import java.util.ArrayList;

public class MyDeque {

private ArrayList data = new ArrayList<>();

public void addFront(int value) {

data.add(0, value);

}

public void addRear(int value) {

data.add(value);

}

public int removeFront() {

return data.remove(0);

}

public int removeRear() {

return data.remove(data.size() - 1);

}

}


#### Advantages of Java's ArrayList-based deque:

- Constant time complexity for addFront(), addRear(), and removeFront() operations (O(1))
- Linear time complexity for removeRear() operation (O(n)) due to the use of an array

### Deque Implementation in C and C++

In C and C++, a deque can be implemented using dynamic arrays or linked lists:

#include

#include

typedef struct Node {

int data;

struct Node* next;

} Node;

Node* create_node(int value) {

Node new_node = (Node)malloc(sizeof(Node));

new_node->data = value;

new_node->next = NULL;

return new_node;

}

void add_front(Node head, int value) {

Node* new_node = create_node(value);

new_node->next = *head;

*head = new_node;

}

void add_rear(Node head, int value) {

Node* new_node = create_node(value);

if (*head == NULL) {

*head = new_node;

return;

}

Node current = head;

while (current->next != NULL) {

current = current->next;

}

current->next = new_node;

}

int remove_front(Node head) {

if (*head == NULL) {

printf("Deque is empty.\n");

return -1;

}

int value = (*head)->data;

Node temp = head;

head = (head)->next;

free(temp);

return value;

}

int remove_rear(Node head) {

if (*head == NULL) {

printf("Deque is empty.\n");

return -1;

}

if ((*head)->next == NULL) {

int value = (*head)->data;

free(*head);

*head = NULL;

return value;

}

Node current = head;

while (current->next->next != NULL) {

current = current->next;

}

int value = current->next->data;

free(current->next);

current->next = NULL;

return value;

}


#### Advantages of C/C++ linked list-based deque:

- Constant time complexity for addFront(), addRear(), removeFront(), and removeRear() operations (O(1) for average case, O(n) for worst case) due to the use of a linked list. However, memory management must be handled carefully to avoid leaks.

Worked Example

Python Deque Implementation

from collections import deque

Creating a deque and adding elements

my_deque = deque([1, 2, 3])

Inserting an element at the front

my_deque.appendleft(0)

print("Deque after appending 0: ", my_deque)

Removing elements from both ends

my_deque.pop()

my_deque.popleft()

print("Deque after popping from rear and front: ", my_deque)


### Java Deque Implementation

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {

MyDeque deque = new MyDeque();

deque.addRear(1);

deque.addRear(2);

deque.addRear(3);

System.out.println("Deque after creation: " + deque);

deque.addFront(0);

System.out.println("Deque after appending 0: " + deque);

deque.removeRear();

System.out.println("Deque after popping from rear: " + deque);

deque.removeFront();

System.out.println("Deque after popping from front: " + deque);

}

}


### C Deque Implementation

#include

#include

typedef struct Node {

int data;

struct Node* next;

} Node;

int main() {

Node* head = NULL;

add_rear(&head, 1);

add_rear(&head, 2);

add_rear(&head, 3);

printf("Deque after creation: ");

print_deque(head);

add_front(&head, 0);

printf("\nDeque after appending 0: ");

print_deque(head);

remove_rear(&head);

printf("\nDeque after popping from rear: ");

print_deque(head);

remove_front(&head);

printf("\nDeque after popping from front: ");

print_deque(head);

return 0;

}

Common Mistakes

  1. Forgetting to initialize the deque or head pointer in C/C++
  2. Using push() and pop() instead of append(), appendleft(), popleft(), and pop() in Python
  3. Mixing up front and rear operations in Java, C, or C++
  4. Failing to handle empty deques when removing elements
  5. Not properly managing memory allocation and deallocation in C/C++ implementations
  6. Incorrectly implementing custom linked list-based deque in C/C++
  7. Misunderstanding the time complexity of various operations, leading to inefficient code
  8. Neglecting to validate input data when adding elements to the deque
  9. Implementing a deque without considering the specific use case and its requirements (e.g., using an array-based deque for frequent insertions at one end)
  10. Failing to optimize the deque implementation for the target programming language or platform

Practice Questions

  1. Implement a deque using a linked list in Python.
  2. Write a function that checks if two given deques are equal in Java.
  3. Implement a deque using dynamic arrays in C++.
  4. Given a deque, write a function to reverse the order of elements in C.
  5. Write a Python program that implements a deque and uses it to simulate a simple undo/redo system for text editing.
  6. Implement a priority queue using a deque in Java.
  7. Implement a LRU (Least Recently Used) cache using a deque in C++.
  8. Write a function that calculates the median of a list using a deque in Python.
  9. Compare the performance of an array-based deque and linked list-based deque for various operations in different programming languages.
  10. Implement a custom deque data structure that supports both insertion and deletion at arbitrary positions in C++.

FAQ

What is the time complexity of append(), appendleft(), popleft(), and pop() operations on a Python deque?

  • append(): O(1)
  • appendleft(): O(1)
  • popleft(): O(1)
  • pop(): O(n) for average case, O(1) for amortized analysis

What is the advantage of using a deque over a stack or queue?

  • A deque allows insertions and deletions from both ends, making it more flexible in scenarios where frequent operations at either end are required.

Can I use a Python list as a deque?

  • While a list can be used to simulate a deque, it is not as efficient because it does not support constant-time insertions and deletions from both ends like the built-in deque data structure.

How would you implement a FIFO cache using a deque in Java?

  • Create a deque to store the cached items, with the order of insertion representing the order of removal (FIFO). When adding an item, if the deque reaches its maximum size, remove the item at the front before adding the new one.

How can I implement a priority queue using a deque in C++?

  • Implement a custom node structure that includes both data and priority fields. Maintain the nodes in the deque sorted by their priorities (highest priority first for max-heap or lowest priority first for min-heap). Use a compare function to sort the nodes during insertion and removal operations.

What is the time complexity of a custom linked list-based deque implementation in C/C++?

  • Constant time complexity for addFront(), addRear(), removeFront(), and removeRear() operations (O(1) for average case, O(n) for worst case) due to the use of a linked list. However, memory management must be handled carefully to avoid leaks.

How does the choice of data structure (array or linked list) affect the performance of a deque implementation in C/C++?

  • Using an array as the underlying data structure can lead to faster insertions and deletions at one end, but slower operations at the other end due to the need for shifting elements. On the other hand, using a linked list allows constant-time insertions and deletions from either end, but with potential memory fragmentation and slower access times compared to arrays.

What are some potential applications of deques in real-world programming scenarios?

  • Network packet processing, web browser history management, undo/redo operations in text editors, priority queues for scheduling tasks, and implementing LRU caches are examples of real-world scenarios where deques can be useful.
Deque Implementation in Python, Java, C, and C++ | Data Structures & Algorithms | XQA Learn