Leecode 0232. Implement Queue using Stacks
232. Implement Queue using Stacks
Implement a first in first out (FIFO) queue using only two Stacks. The implemented queue should support all the functions of a normal queue (push
, peek
, pop
, and empty
).
Implement the MyQueue
class:
void push(int x)
Pushes element x to the back of the queue.int pop()
Removes the element from the front of the queue and returns it.int peek()
Returns the element at the front of the queue.boolean empty()
Returnstrue
if the queue is empty,false
otherwise.
Notes:
- You must use only standard operations of a Stacks, which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, the Stacks may not be supported natively. You may simulate a Stack using a list or deque (double-ended queue) as long as you use only a Stack's standard operations.
Example 1:
1 | Input |
题目大意
要求仅使用两个栈实现一个 先进先出(FIFO) 的队列,并支持普通队列的全部功能(push
、peek
、pop
、empty
)。
核心限制:只能使用栈的标准操作(仅允许 push
到栈顶、从栈顶 peek
/pop
、获取栈大小、判断栈是否为空),不能使用栈之外的其他数据结构特性。
解题思路
栈的特性是 后进先出(LIFO),而队列是 先进先出(FIFO),通过两个栈的 “配合反转” 可模拟队列:
- 划分功能栈:
in_vec
:专门用于处理push
操作(元素始终压入in_vec
栈顶,模拟队列 “入队到队尾”)。out_vec
:专门用于处理pop
和peek
操作(当out_vec
为空时,将in_vec
的所有元素转移到out_vec
,此时out_vec
的栈顶就是队列的队首,实现 “反转顺序”)。
- 核心逻辑:
push
:直接将元素压入in_vec
(O (1) 时间,仅栈顶操作)。pop
/peek
:先检查out_vec
是否为空,若为空则将in_vec
所有元素 逐个弹出并压入out_vec
(此时out_vec
栈顶为队列队首);再从out_vec
栈顶执行pop
或peek
(转移元素的时间为 O (n),但每个元素仅转移一次,均摊时间为 O (1))。empty
:当两个栈均为空时,队列才为空(O (1) 时间)。
1 | #include <vector> |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.