Implements a queue using two stacks. Lazily reverses items from the back_stack to the front_stack when needed.
| 5 | """ |
| 6 | |
| 7 | class MyQueue(object): |
| 8 | """ |
| 9 | Implements a queue using two stacks. |
| 10 | Lazily reverses items from the back_stack to the front_stack when needed. |
| 11 | """ |
| 12 | def __init__(self): |
| 13 | self.front_stack = Stack() |
| 14 | self.back_stack = Stack() |
| 15 | |
| 16 | def eq(self, data): |
| 17 | self.back_stack.push(data) |
| 18 | |
| 19 | def dq(self): |
| 20 | if self.front_stack.size == 0: |
| 21 | self.rebuild() |
| 22 | return self.front_stack.pop() |
| 23 | |
| 24 | def peek_front(self): |
| 25 | if self.front_stack.size == 0: |
| 26 | self.rebuild() |
| 27 | return self.front_stack.peek() |
| 28 | |
| 29 | def rebuild(self): |
| 30 | """ |
| 31 | Lazily rebuilds the front stack when a value is needed by pop/peek. |
| 32 | When the front_stack empties, rebuild it by reversing the values in |
| 33 | the back_stack. |
| 34 | """ |
| 35 | while self.back_stack.size > 0: |
| 36 | self.front_stack.push(self.back_stack.pop()) |
| 37 | |
| 38 | |
| 39 |