Create a program that implements a deque (double-ended queue).
- User
Create a program that implements a deque (double-ended queue).
Assistant
Create a program that implements a deque (double-ended queue).
The user wants a program that implements a deque (double-ended queue).
1. Understand the Goal: The core request is to create a Deque data structure. A deque supports insertion and deletion at both the front and the rear. Key operations:
addFront(item)addRear(item)removeFront()removeRear()isEmpty()size()2. Choose a Programming Language:
Python is generally the most accessible for data structure demonstrations due to its readability, but C++ or Java are also common for lower-level implementation details (like linked lists vs. dynamic arrays).
I will provide the solution in Python because it's concise, but I'll implement it using a Doubly Linked List logic (or simply a list) to show how it works under the hood, rather than just importing collections.deque.
Self-correction: Python's built-in list is actually not efficient for addFront (). A true Deque should have operations.
Option A: Use Python's collections.deque. (Too trivial, doesn't "implement" it).
Option B: Use a Python list as a circular buffer or just a dynamic array (inefficient front ops).
Option C: Implement a Node-based Doubly Linked List in Python. This is usually the best way to demonstrate understanding of the data structure mechanics.
Option D: Provide implementations in multiple languages (e.g., Python and C++).
Let's stick to a clean Python implementation using a Class, simulating the behavior. If I use a Python list, I should warn about performance. Better yet, I will implement it using a Doubly Linked List concept within Python for correctness and efficiency, or just use the standard list with a caveat if simplicity is preferred.
Actually, for a general "Create a program" request, a Python class wrapping a list is the most common "educational" answer, even if pop(0) is . However, a Doubly Linked List is the "proper" computer science way.
Let's provide a Python implementation using a Class.
I will also include a C++ implementation because C++ pointers are often associated with learning how deques work at a lower level.
3. Structure of the Python Solution (Doubly Linked List Approach):
Node class: stores data, next pointer, prev pointer.Deque class:
__init__: head, tail, size.addFront: Create node. If empty, head=tail=node. Else, node.next=head, head.prev=node, head=node.addRear: Create node. If empty, head=tail=node. Else, tail.next=node, node.prev=tail, tail=node.removeFront: Check empty. Store data. Move head to head.next. If new head exists, head.prev=None. Else (list now empty), tail=None.removeRear: Check empty. Store data. Move tail to tail.prev. If new tail exists, tail.next=None. Else, tail=None.peekFront, peekRear, isEmpty.4. Structure of the Python Solution (Simple List Approach - for contrast):
Often, simple interview questions accept list.append and list.pop for rear, and list.insert(0) and list.pop(0) for front. But I should advise against this for production.
Decision: I will provide a Python implementation using a Doubly Linked List logic (manual Node management) because it guarantees time complexity for all operations, which is the definition of a performant Deque.
5. Drafting the Code (Mental or Scratchpad):
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class Deque:
def __init__(self):
self.head = None
self.tail = None
self._size = 0
def addFront(self, item):
new_node = Node(item)
if self.isEmpty():
self.head = new_node
self.tail = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
self._size += 1
# ... other methods ...
6. Refining the Output:
7. Alternative Language (C++):
It might be helpful to show a C++ version using std::list or a custom class since memory management makes the "implementation" aspect more explicit. I'll stick to Python as the primary answer but maybe write it in a way that translates easily to other OO languages.
Let's stick to Python. It's the most widely understood for these types of generic requests.
8. Final Polish of the Python Code:
__len__ and __str__ for better usability.9. Writing the Response:
Let's write the code.
class Deque:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def add_front(self, item):
self.items.insert(0, item)
def add_rear(self, item):
self.items.append(item)
def remove_front(self):
if self.is_empty():
return None
return self.items.pop(0)
def remove_rear(self):
if self.is_empty():
return None
return self.items.pop()
Critique of List implementation: insert(0, item) and pop(0) are . This is technically a Deque interface, but not a performant implementation.
Better Implementation: Use collections.deque inside? No, that defeats the purpose of "creating" it.
Best Implementation: Doubly Linked List.
Let's provide the Doubly Linked List implementation in Python. It demonstrates the actual mechanics of pointers shifting.
Steps for the Linked List logic:
addFront: New node points to current head. Update head.prev to new node. Update head to new node.addRear: Current tail points to new node. Update new node prev to tail. Update tail to new node.removeFront: Save head value. Move head to head.next. If head is not None, head.prev = None. Else (empty), tail = None.removeRear: Save tail value. Move tail to tail.prev. If tail is not None, tail.next = None. Else (empty), head = None.This is robust.
Final Plan:
Node class.Deque class.add_front, add_rear, remove_front, remove_rear, is_empty, size.To ensure the operations are efficient ( time complexity), this implementation uses a Doubly Linked List rather than a standard Python list (which would be for adding/removing items from the front).
Node class that contains a value, a pointer to the next node, and a pointer to the prev (previous) node.Deque class maintains two main pointers:
head: Points to the start of the line.tail: Points to the end of the line.head.tail.head pointer to the next node and disconnects the old head.tail pointer to the previous node and disconnects the old tail.This ensures that no matter where you add or remove data, the operation happens instantly (Constant Time ), unlike a standard Python list where removing from the front requires shifting every other element in memory.
class Node:
"""A helper class to represent a node in the doubly linked list."""
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class Deque:
"""Implementation of a Double-Ended Queue using a Doubly Linked List."""
def __init__(self):
self.head = None
self.tail = None
self._size = 0
def add_front(self, item):
"""
Adds an item to the front of the deque.
Time Complexity: O(1)
"""
new_node = Node(item)
if self.is_empty():
self.head = new_node
self.tail = new_node
else:
# Link new node to the current head
new_node.next = self.head
self.head.prev = new_node
# Update head pointer
self.head = new_node
self._size += 1
def add_rear(self, item):
"""
Adds an item to the back (rear) of the deque.
Time Complexity: O(1)
"""
new_node = Node(item)
if self.is_empty():
self.head = new_node
self.tail = new_node
else:
# Link new node to the current tail
self.tail.next = new_node
new_node.prev = self.tail
# Update tail pointer
self.tail = new_node
self._size += 1
def remove_front(self):
"""
Removes and returns the item from the front.
Raises Exception if deque is empty.
Time Complexity: O(1)
"""
if self.is_empty():
raise Exception("Remove from empty deque")
value = self.head.value
# If only one item exists
if self.head == self.tail:
self.head = None
self.tail = None
else:
# Move head pointer forward
self.head = self.head.next
# Sever link to old head
self.head.prev = None
self._size -= 1
return value
def remove_rear(self):
"""
Removes and returns the item from the back.
Raises Exception if deque is empty.
Time Complexity: O(1)
"""
if self.is_empty():
raise Exception("Remove from empty deque")
value = self.tail.value
# If only one item exists
if self.head == self.tail:
self.head = None
self.tail = None
else:
# Move tail pointer backward
self.tail = self.tail.prev
# Sever link to old tail
self.tail.next = None
self._size -= 1
return value
def is_empty(self):
"""Returns True if the deque is empty."""
return self._size == 0
def size(self):
"""Returns the number of items in the deque."""
return self._size
def peek_front(self):
"""Returns the front item without removing it."""
if self.is_empty():
return None
return self.head.value
def peek_rear(self):
"""Returns the rear item without removing it."""
if self.is_empty():
return None
return self.tail.value
def __str__(self):
"""Returns a string representation of the deque (Front -> Rear)."""
items = []
current = self.head
while current:
items.append(str(current.value))
current = current.next
return "Front -> " + " <-> ".join(items) + " <- Rear"
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
d = Deque()
print("1. Adding elements:")
d.add_rear(10) # Deque: 10
d.add_front(5) # Deque: 5, 10
d.add_rear(20) # Deque: 5, 10, 20
d.add_front(1) # Deque: 1, 5, 10, 20
print(d)
print(f"Size: {d.size()}")
print("\n2. Removing elements:")
print(f"Remove Front: {d.remove_front()}") # Removes 1
print(f"Remove Rear: {d.remove_rear()}") # Removes 20
print(d)
print("\n3. Peeking:")
print(f"Peek Front: {d.peek_front()}") # Should be 5
print(f"Peek Rear: {d.peek_rear()}") # Should be 10