https://www.geeksforgeeks.org/implement-stack-using-queue/ >>> stack = StackWithQueues() >>> stack.push(1) >>> stack.push(2) >>> stack.push(3) >>> stack.peek() 3 >>> stack.pop() 3 >>> stack.peek() 2 >>> stack.pop() 2 >>> stack.pop() 1
| 6 | |
| 7 | @dataclass |
| 8 | class StackWithQueues: |
| 9 | """ |
| 10 | https://www.geeksforgeeks.org/implement-stack-using-queue/ |
| 11 | |
| 12 | >>> stack = StackWithQueues() |
| 13 | >>> stack.push(1) |
| 14 | >>> stack.push(2) |
| 15 | >>> stack.push(3) |
| 16 | >>> stack.peek() |
| 17 | 3 |
| 18 | >>> stack.pop() |
| 19 | 3 |
| 20 | >>> stack.peek() |
| 21 | 2 |
| 22 | >>> stack.pop() |
| 23 | 2 |
| 24 | >>> stack.pop() |
| 25 | 1 |
| 26 | >>> stack.peek() is None |
| 27 | True |
| 28 | >>> stack.pop() |
| 29 | Traceback (most recent call last): |
| 30 | ... |
| 31 | IndexError: pop from an empty deque |
| 32 | """ |
| 33 | |
| 34 | main_queue: deque[int] = field(default_factory=deque) |
| 35 | temp_queue: deque[int] = field(default_factory=deque) |
| 36 | |
| 37 | def push(self, item: int) -> None: |
| 38 | self.temp_queue.append(item) |
| 39 | while self.main_queue: |
| 40 | self.temp_queue.append(self.main_queue.popleft()) |
| 41 | self.main_queue, self.temp_queue = self.temp_queue, self.main_queue |
| 42 | |
| 43 | def pop(self) -> int: |
| 44 | return self.main_queue.popleft() |
| 45 | |
| 46 | def peek(self) -> int | None: |
| 47 | return self.main_queue[0] if self.main_queue else None |
| 48 | |
| 49 | |
| 50 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected