两个栈实现队列

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路
朴素的想法: stack1用来存元素,每次push新元素进stack1, 队列pop的时候先将stack1的所有元素pop, 并push进stack2, res = stack2.pop(), 接着再将stack2中所有的元素pop,并push进stack1。

正解: 队列是先进先出,栈是先进后出,如何用两个栈来实现这种先进先出呢?
其实很简单,我们假设用stack1专门来装元素,那么直接stack1.pop肯定是不行的,这个时候stack2就要发挥作用了。

我们的规则是:只要stack2中有元素就pop,如果stack2为空,则将stack1中所有元素倒进satck2中,就是说,新元素只进stack1,元素出来只从stack2出来。

这样子,就能保证每次从stack2中pop出来的元素就是最老的元素了。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Stack;

public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
stack1.push(node);
}

public int pop() {
if( stack2.isEmpty() ){
while( !stack1.isEmpty() ){
stack2.push( stack1.pop() );
}
}
return stack2.pop();
}
}
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!

扫一扫,分享到微信

微信分享二维码
  • © 2020 Zhang-Ke
  • Powered by Hexo Theme Ayer
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信