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
).
Implement the MyStack
class:
void push(int x)
Pushes element x to the top of the stack.int pop()
Removes the element on the top of the stack and returns it.int top()
Returns the element on the top of the stack.boolean empty()
Returns true if the stack is empty, false otherwise.Notes:
push to back
, peek/pop from front
, size
and is empty
operations are valid.from collections import deque
class MyStack:
def __init__(self):
self.q = deque()
def push(self, x: int) -> None:
self.q.append(x)
for _ in range(len(self.q) - 1):
self.q.rotate(-1)
def pop(self) -> int:
return self.q.popleft()
def top(self) -> int:
return self.q[0]
def empty(self) -> bool:
if self.q:
return False
else:
return True
그냥 stack을 구현해도 풀리긴 한다.
class MyStack:
def __init__(self):
self.st = []
def push(self, x: int) -> None:
self.st.append(x)
def pop(self) -> int:
return self.st.pop()
def top(self) -> int:
return self.st[-1]
def empty(self) -> bool:
if self.st:
return False
else:
return True