Open nmusgrave opened 8 years ago
cake: stack using 2 queues import queue ''' Implement stack using 2 queues assume queue gives O(1) push and pop ''' class Stack: def init(self): self.q1 = queue.Queue() self.q2 = queue.Queue() self.size = 0
# insert at top of stack
def push(self, value):
self.q1.put(value)
self.size += 1
# remove from top of stack
def pop(self):
self.q2.empty()
for i in range(self.size - 1):
self.q2.put(self.q1.get())
result = self.q1.get()
assert(self.q1.empty())
self.size = self.size - 1
for i in range(self.size):
self.q1.put(self.q2.get())
assert(self.q2.empty())
return result
s = Stack()
s.push(4)
s.push(5)
print(s.pop(), ' == 5?')
print(s.pop(), ' == 4?')