Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
두 개의 큐를 이용해서 스택의 push, top, pop, empty의 기능을 구현하는 문제이다.
파이썬의 deque를 이용하여 문제를 풀었다.
from collections import deque
class MyStack(object):
def __init__(self):
self.stack = deque()
def push(self, x):
self.stack.append(x)
def pop(self):
for i in range(len(self.stack) - 1):
self.stack.append(self.stack.popleft())
return self.stack.popleft()
def top(self):
for i in range(len(self.stack) - 1):
self.stack.append(self.stack.popleft())
top = self.stack.popleft()
self.stack.append(top)
return top
def empty(self):
return len(self.stack) == 0