使用队列实现栈的下列操作:
push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空
注意:
你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
解法 1
由于队列是先进后出,所以某元素 q 入队后肯定处于队尾位置,需要将 q 前面的元素逐个弹出并重新入队,从而将元素 q 排列到队首位置,这样就实现了栈的先进先出效果。
from collections import deque
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = deque()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.queue.appendleft(x)
for i in range(len(self.queue) - 1):
self.queue.appendleft(self.queue.pop())
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.queue.pop()
def top(self) -> int:
"""
Get the top element.
"""
return self.queue.__getitem__(-1)
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return not self.queue
执行用时 :44 ms
内存消耗 :13.7 MB
时间复杂度:每个元素入队时,都要将前面的元素弹出并重新入队,时间复杂度都为 O(n),队列的弹出、索引和判断空操作的时间复杂度都为 O(1)
空间复杂度:O(1)
参考
https://leetcode-cn.com/problems/implement-stack-using-queues/










网友评论