- 剑指Offer 59 - II. 队列的最大值(Medium)
- 剑指Offer 30. 包含min函数的栈(Easy) 、155. 最小栈(Easy)
- 232. 用2个栈实现队列(push、pop、peek、empty)(Easy)
【题目链接】
题解
思路
代码
class CQueue:
### 1130 辅助栈(456 ms,17 MB)
def __init__(self):
# 当且仅当B中为空时,才会将A中元素全部传入B中(即若B中元素没全部出栈时,A中的元素是会持续积压的)
self.A, self.B = [], []
def appendTail(self, value: int) -> None:
self.A.append(value)
def deleteHead(self) -> int:
# 若B中还有元素,则出栈
if self.B: return self.B.pop()
# 若B为空且若A为空,则返回-1
if not self.A: return -1
# 若B为空,但A非空,则将A中所有元素传入B,然后B出栈
while self.A:
self.B.append(self.A.pop())
return self.B.pop()
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
225. 用队列实现栈
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue1 = collections.deque() # 用于存储栈内的元素
self.queue2 = collections.deque() # 作为入栈操作的辅助队列
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
# 入栈操作时,首先将元素入队到queue2,
self.queue2.append(x)
# 再把queue1中所有元素出队加入queue2,相当于把需要Push的元素放在栈顶
while self.queue1:
self.queue2.append(self.queue1.popleft())
# 交换两个队列,使得push相当于每次在前面加元素
self.queue1, self.queue2 = self.queue2, self.queue1
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.queue1.popleft()
def top(self) -> int:
"""
Get the top element.
"""
return self.queue1[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return not self.queue1