class Queue: def __init__(self): self._enqueue = Stack() self._dequeue = Stack() def is_empty(self): return self._enqueue.is_empty() and self._dequeue.is_empty() def size(self): return self._dequeue.size() + self._enqueue.size() def enqueue(self, item): self._enqueue.push(item) def dequeue(self): if self._dequeue.is_empty(): while not self._enqueue.is_empty(): self._dequeue.push(self._enqueue.pop()) return self._dequeue.pop() def stdout(self): print('_enqueue') self._enqueue.stdout() print('_dequeue') self._dequeue.stdout()
class StackQueue: """ Implementation of Queue using two Stacks. """ def __init__(self, limit=10): self.limit = limit self.stack_one = Stack(limit) self.stack_two = Stack(limit) def enqueue(self, item): if self.isFull(): raise QueueOverflowError("Cannot insert item in a full queue.") self.stack_one.push(item) def _move_item_to_second_stack(self): if self.stack_two.is_empty(): while not self.stack_one.is_empty(): self.stack_two.push(self.stack_one.pop()) def dequeue(self): if self.isEmpty(): raise QueueUnderflowError( "Cannot Remove an item from empty Queue.") self._move_item_to_second_stack() return self.stack_two.pop() def peek(self): self._move_item_to_second_stack() return self.stack_two.peek() def isEmpty(self): return self.stack_one.is_empty() and self.stack_two.is_empty() def isFull(self): return (self.stack_one.size() + self.stack_two.size()) >= self.limit
def reverse_list(arr): stack = Stack() reversed = [] for item in arr: stack.push(item) while stack.size() > 0: reversed.append(stack.pop()) return reversed