Open In App

Implementation of Deque using Doubly Linked List in Python

Last Updated : 08 Feb, 2025
Suggest changes
Share
Like Article
Like
Report

A deque (double-ended queue) is a linear data structure that allows insertion and deletion from both the front and rear efficiently. A Doubly Linked List (DLL) is a preferred choice for implementing a deque as it enables O(1) insertion and deletion without shifting elements, unlike lists.

deque_dll

Node Structure

A Doubly Linked List consists of nodes where each node contains:

  • Data (the value stored)
  • Pointer to the next node
  • Pointer to the previous node
Python
class Node: def __init__(self, key): self.key = key self.next = None self.prev = None 

Operations Explained

1. Insertion at Rear (insert_rear(x)):

  • Creates a new node and inserts it at the rear.
  • Updates pointers accordingly.

2. Deletion from Front (delete_front()):

  • Removes the front node and updates pointers.
  • Returns None if the deque is empty.

3. Displaying Deque (display()):

  • Traverses the list from front to rear and returns elements.

4. Checking Size (get_size()):

  • Returns the number of elements in the deque.

5. Checking if Empty (is_empty()):

  • Returns True if the deque is empty, otherwise False

Deque Implementation Using Doubly Linked List

Python
class Node: def __init__(self, key): self.key = key self.next = None self.prev = None class MyDeque: def __init__(self): self.front = None self.rear = None self.size = 0 def insert_rear(self, x): temp = Node(x) if self.rear is None: self.front = self.rear = temp else: self.rear.next = temp temp.prev = self.rear self.rear = temp self.size += 1 def delete_front(self): if self.front is None: return None else: res = self.front.key self.front = self.front.next if self.front is None: self.rear = None else: self.front.prev = None self.size -= 1 return res def get_size(self): return self.size def is_empty(self): return self.size == 0 def display(self): temp = self.front elements = [] while temp: elements.append(temp.key) temp = temp.next return elements # Example Usage dq = MyDeque() dq.insert_rear(10) dq.insert_rear(20) dq.insert_rear(30) print("Deque after insertions:", dq.display()) print("Deleted from front:", dq.delete_front()) print("Deque after deletion:", dq.display()) 

Output
Deque after insertions: [10, 20, 30] Deleted from front: 10 Deque after deletion: [20, 30] 

Complexity Analysis

OperationTime Complexity
Insert at FrontO(1)
Insert at RearO(1)
Delete from FrontO(1)
Delete from RearO(1)
Get SizeO(1)
Check if EmptyO(1)
Display ElementsO(n)

Next Article

Similar Reads

Article Tags :
Practice Tags :