Amazon Interview Question

Implement a Queue data structure and provide enQ and deQ functionality where the only data structure you have to use is stack.

Interview Answers

Anonymous

Apr 6, 2012

Use 2 stacks. enQ into the first stack and deQ from the second. When the second stack is empty, pop and push every element of the first into the second.

2

Anonymous

Oct 12, 2018

#python: use stack to create queue class Queue(object): def __init__(self,): self.stack = [] #stack.pop and stack.append is a stack def print_queue(self, ): tmp_stack = [] while self.stack: item = self.stack.pop() tmp_stack.append(item) print(f"- {item}") while tmp_stack: self.stack.append(tmp_stack.pop()) def push(self, item): temp_stack = [] while self.stack: temp_stack.append(self.stack.pop()) self.stack.append(item) while temp_stack: self.stack.append(temp_stack.pop()) def pop(self,): tmp_stack = [] if not self.stack: return self.stack.pop() while self.stack: last_item = self.stack.pop() tmp_stack.append(last_item) tmp_stack.pop() #pop the last item print(f"tmp {tmp_stack}") while tmp_stack: self.stack.append(tmp_stack.pop()) return last_item q = Queue() q.push(1) q.push(2) q.push(3) print(q.pop()) q.print_queue()