MCPcopy Create free account
hub / github.com/careercup/ctci / MyQueue

Class MyQueue

python/Chapter 3/Question3_5/3_5.py:7–36  ·  view source on GitHub ↗

Implements a queue using two stacks. Lazily reverses items from the back_stack to the front_stack when needed.

Source from the content-addressed store, hash-verified

5"""
6
7class 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

Callers 1

3_5.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected