【LeetCode】225. Implement Stack using Queues 解题记录
问题描述
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
- void push(int x) Pushes element x to the top of the stack.
- int pop() Removes the element on the top of the stack and returns it.
- int top() Returns the element on the top of the stack.
- boolean empty() Returns true if the stack is empty, false otherwise.
Notes:
- You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
- Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue’s standard operations.
测试样例
1 | Input |
说明
1 | 1 <= x <= 9 |
解题
思路
只要保证每次 push
后,新元素都处于队头位置即可,pop
和 top
取队头元素即可。
push
新元素:
- 将新元素加入队尾
- 取队头元素并将其加入队尾,直到队头为新加入的元素
补充:
- 队列
- 时间复杂度
push = O(n), pop = O(1)
代码
1 | import java.util.Queue; |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哆啦 C 梦!
评论