Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Implement the Queue Abstract Data Type using two stacks as instance variables. Recall that a Queue Q supports Q.enqueue(e), Q.dequeue(), Q.first(), Q.is empty() and len(Q).
Implement the Queue Abstract Data Type using two stacks as instance variables. Recall that a Queue Q supports Q.enqueue(e), Q.dequeue(), Q.first(), Q.is empty() and len(Q).
# Abstract Data Type : Queue # Queue Q supports # Q.enqueue(e): add element e to the back of the queue Q # Q.dequeue(e): remove and return the first element of the queue Q # Q.first(): return a reference to the first element of the queue Q # Q.is_empty(): return true if Q does not contain any elements # len(Q): return number of elements in Q # We implement circular lists using mod(len(Q)) -> using % operator class Empty(Exception): pass class ArrayQueue: """Circular FIFO Queue""" def __init__(self, capacity): self._data = [None] * capacity self._size = 0 # number of elements (NOT size of list) self._front = 0 # index of the first element in queue def __len__(self): return self._size def is_empty(self): return self._size == 0 def first(self): if self.is_empty(): raise Empty("Queue is empty") return self._data[self._front] def dequeue(self): if self.is_empty(): raise Empty("Queue is empty") element_to_dequeue = self._data[self._front] self._data[self._front] = None self._front = (self._front + 1) % len(self._data) # implementing circular behavior self._size -= 1 # if size of queue is less that 1/4 capacity reduce the queue size to half if 0 < self._size < len(self._data) // 4: self._resize(len(self._data)//2) return element_to_dequeue def _resize(self, capacity): temp = self._data self._data = [None] * capacity step = self._front for k in range(self._size): self._data[k] = temp[step] step = (step + 1) % len(temp) self._front = 0 def enqueue(self, e): if self._size == len(self._data): self._resize(2*len(self._data)) idx_to_enqueue = (self._front + self._size) % len(self._data) self._data[idx_to_enqueue] = e self._size += 1
The exercise did not give us more informations
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started