原题链接:
225: Implement Stack using Queses
232: Implement Queue using Stacks
解题思路:就是用两个栈相互倒来实现队列的功能。也可以只用一个栈实现,但是个人感觉那样不如两个栈好理解,方便记忆。入队的时间复杂度是O(1),出队是O(n)
用栈来实现队列:
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stackA = []
self.stackB = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.stackA.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
while len(self.stackA) > 1:
self.stackB.append(self.stackA.pop())
a = self.stackA.pop()
while self.stackB:
self.stackA.append(self.stackB.pop())
return a
def peek(self) -> int:
"""
Get the front element.
"""
while self.stackA:
self.stackB.append(self.stackA.pop())
a = self.stackB.pop()
self.stackA.append(a)
while self.stackB:
self.stackA.append(self.stackB.pop())
return a
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self.stackA == [] and self.stackB == []
用队列来实现栈:
需要注意的是在top这个操作里,要先把队列末尾的元素a拿出去,然后再放回队列中。
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queueA = []
self.queueB = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.queueA.append(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
if not self.queueA:
return None
while len(self.queueA) != 1:
self.queueB.append(self.queueA.pop(0))
self.queueA, self.queueB = self.queueB, self.queueA
return self.queueB.pop()
def top(self) -> int:
"""
Get the top element.
"""
while len(self.queueA) > 1:
self.queueB.append(self.queueA.pop(0))
a = self.queueA.pop(0)
self.queueB.append(a)
self.queueA, self.queueB = self.queueB, self.queueA
return a
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return self.queueA == []