题目:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
示例:
输入: [“MyStack”, “push”, “push”, “top”, “pop”, “empty”] [[], [1], [2],[], [], []]
输出: [null, null, null, 2, 2, false]
解释:
MyStack myStack =new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); //返回2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
思路:
用队列实现栈,队列是先入先出的,栈是先入后出,后入先出的,所以可以先生成一个空列表来模拟队列,然后放里边放元素,正常往队列里放就是往后边放,先加进来,然后把加进来这个元素前面的元素依次出队再入队,刚加进来的元素就变成了第一个,出栈的时候就实现了后进先出。
直接进行出队操作,判空操作,读取第一个元素操作即可。
from collections import deque
class MyStack(object):
def __init__(self):# 顺序存储实现,使用列表模拟一个队列
"""
Initialize your data structure here.
"""
self.queue = deque()#空列表
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
# 按照队列的逻辑,后入一个元素,实现栈就是后入的要先出,原队列的元素顺序保留
# 先入一个元素,然后原队列中的元素依次出队,再入队
self.queue.append(x)
for i in range(len(self.queue) - 1):
self.queue.append(self.queue.popleft())
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
# 直接出队,就实现栈的操作
return self.queue.popleft()
def top(self):
"""
Get the top element.
:rtype: int
"""
return self.queue[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not self.queue
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()