题目:
解法一:
from queue import Queue
class MyStack:
# 思路一:
# 1.初始化一个队列为空,每次pop把另一个队列前n-1个元素,移动到为空的队列,然后输出最后一个元素,即为栈顶元素;一轮操作过后需要交换输入输出队列
# 2.push时,把最新进队列的元素标记为栈顶元素
def __init__(self):
"""
Initialize your data structure here.
"""
self.input_que = Queue()
self.out_que = Queue()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.input_que.put(x)
self.top_e = x
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
while (self.input_que.qsize() > 1):
self.top_e = self.input_que.get() # 比如1,2,3依次入队列,当3被pop后,2就是栈顶元素
self.out_que.put(self.top_e)
top = self.input_que.get()
self.input_que, self.out_que = self.out_que, self.input_que
return top
def top(self) -> int:
"""
Get the top element.
"""
return self.top_e
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return self.input_que.empty() and self.out_que.empty()
解法二:
from queue import Queue
class MyStack:
# # 思路二:使用list,反转list元素; 虽然能提交但有点问题?比如输入3个数1,2,3,经过反转后3,1,2?但leedcode上没有三个数的测试案例
def __init__(self):
"""
Initialize your data structure here.
"""
self.input = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.input.append(x)
k = len(self.input)
while k>1:
self.input.append(self.input.pop(0))
k -= 1
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.input.pop(0)
def top(self) -> int:
"""
Get the top element.
"""
return self.input[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return not bool(self.input)