class MyQueue: def __init__(self): self.new_stack = Stack() self.old_stack = Stack() def _shift_stacks(self): if self.old_stack.is_empty(): while not self.new_stack.is_empty(): self.old_stack.push(self.new_stack.pop()) def add(self, value): return self.new_stack.push(value) def peek(self): if self.is_empty(): return False self._shift_stacks() return self.old_stack.peek() def remove(self): if self.is_empty(): return False self._shift_stacks() return self.old_stack.pop() def is_empty(self): return len(self) == 0 def __len__(self): return len(self.new_stack) + len(self.old_stack)
class SortedStack(Stack): def __init__(self): super().__init__() self.temp_stack = Stack() def push(self, item): if self.is_empty() or item < self.peek(): super().push(item) else: while self.peek() is not None and item > self.peek(): self.temp_stack.push(self.pop()) super().push(item) while not self.temp_stack.is_empty(): super().push(self.temp_stack.pop())