使用队列实现栈的下列操作:
注意:
push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。from collections import deque
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.stack.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
return self.stack.pop()
def top(self):
"""
Get the top element.
:rtype: int
"""
try:
t = self.pop()
self.stack.append(t)
return t
except IndexError:
raise IndexError('empty')
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
try:
self.top()
return False
except IndexError:
return True