说实话,这道题做的有点迷,不清楚哪些是能用的函数,哪些不能用。
后来发现,是自己对数据结构的特点不清楚。
注意:
栈 是 先入后出
队列 是 后入后出
因此,用队列实现栈,我们只能用的是
1、pop(0)(弹出[0])
2、append(录入至[-1])
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack = []
self.pre = []
self.pre2 = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
#templist = [x]
#self.stack = templist + self.stack
self.stack.append(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
self.stack = self.stack[::-1]
res = self.stack.pop(0)
self.stack = self.stack[::-1]
return res
def top(self) -> int:
"""
Get the top element.
"""
print(self.stack)
return self.stack[-1]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
print(self.stack)
return True if self.stack == [] else False