题目描述:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入:
[“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
思路:
两个队列交替着使用,记为 up 和 down,每次push就直接在up上加入,判空就是直接看两个队列是否都空了,每次取pop或者top的时候,先看上面的队列是否为空,不为空则需要的就是上面的队列的最后一个,但是队列每次取都是取最左边,所以把左边的元素都放到down中,直到得到最后一个;若up队列空了就取down中的最后边的一个,做法同上。
代码:
class MyStack(object):
def __init__(self):
self.up = MyQueue()
self.down = MyQueue()
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.up.push(x)
def pop(self):
"""
:rtype: int
"""
if not self.up.isEmpty():
while not self.up.isEmpty():
a = self.up.pop()
if not self.up.isEmpty():
self.down.push(a)
return a
else:
while not self.down.isEmpty():
b = self.down.pop()
if not self.down.isEmpty():
self.up.push(b)
return b
def top(self):
"""
:rtype: int
"""
if not self.up.isEmpty():
while not self.up.isEmpty():
a = self.up.pop()
self.down.push(a)
return a
else:
while not self.down.isEmpty():
b = self.down.pop()
self.up.push(b)
return b
def empty(self):
"""
:rtype: bool
"""
if self.up.isEmpty() and self.down.isEmpty():
return True
else:
return False
class MyQueue(object):
def __init__(self):
self.l = []
def push(self, x):
self.l.append(x)
def pop(self):
a = self.l[0]
del self.l[0]
return a
def peek(self):
return self.l[0]
def isEmpty(self):
return not self.l
官方解法给了另外两种思路:
https://leetcode-cn.com/problems/implement-stack-using-queues/solution/yong-dui-lie-shi-xian-zhan-by-leetcode-solution/
对应链接
方法一:使用两个队列
先把x进入2中,把1中的所有元素一次pop然后进入2中,再把1和2调换,使得1始终和栈中数据应存的形式一样,取1中的pop(即最左端)就是弹栈的操作。
时间复杂度为入栈操作O(n)其余为O(1)。
def push(self, x: int):
"""
Push element x onto stack.
"""
self.queue2.append(x)
while self.queue1:
self.queue2.append(self.queue1.popleft())
self.queue1, self.queue2 = self.queue2, self.queue1
def pop(self):
"""
Removes the element on top of the stack and returns that element.
"""
return self.queue1.popleft()
def top(self):
"""
Get the top element.
"""
return self.queue1[0]
def empty(self):
"""
Returns whether the stack is empty.
"""
return not self.queue1
方法2:使用一个队列,每次把x进入队列后,求队列的长度,把x前面的元素依次pop出来,然后再在进入队列,这样队列中元素的顺序就与栈中应该的顺序相同了,取pop或者top就是队列的pop和peek操作了。
时间复杂度入栈为O(n), 其余为O(1)。
import collections
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = collections.deque()
def push(self, x: int):
"""
Push element x onto stack.
"""
n = len(self.queue)
self.queue.append(x)
for _ in range(n):
self.queue.append(self.queue.popleft())
def pop(self):
"""
Removes the element on top of the stack and returns that element.
"""
return self.queue.popleft()
def top(self):
"""
Get the top element.
"""
return self.queue[0]
def empty(self):
"""
Returns whether the stack is empty.
"""
return not self.queue