一、题目描述
难易程度:简单
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。
二、解题思路
通过下面两步来保持队列的先进先出特点:
- in 栈用来处理入栈(push)操作,out 栈用来处理出栈(pop)操作。
- 当元素要出栈时,需要先将 in 栈元素出栈,并进入 out 栈。
此时元素出栈顺序被反转,因此出栈顺序就和最开始入栈顺序是相同的,先进入的元素先退出,这就是队列的顺序。
复杂度分析
时间复杂度:
- push() 函数为 O(1) ;
- pop() 函数为 O(N) ;
空间复杂度 O(N) : 最差情况下,栈 A 和 B 共保存 N 个元素。
三、代码实现
Stack<Integer> in = new Stack<Integer>();
Stack<Integer> out = new Stack<Integer>();
public void push(int node) {
in.push(node);
}
public int pop() throws Exception {
if (out.isEmpty())
while (!in.isEmpty())
out.push(in.pop());
if (out.isEmpty())
throw new Exception("queue is empty");
return out.pop();
}
推荐阅读
封面
今日算法系列,题解更新地址:studeyang.tech/2023/0720.h…
© 版权声明
文章版权归作者所有,未经允许请勿转载,侵权请联系 admin@trc20.tw 删除。
THE END