题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
思路
入队:入栈(栈1) 出队:将入栈的元素一次出栈到栈2,再pop栈2的首元素
步骤
- 入队:直接入栈
- 出队:判断栈2(删除栈)元素是否为空,若为空,判断栈1元素是否为空,不为空,则将栈1的元素出栈到站2,再将栈2的首元素出栈即可
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() {
// 判断此时删除栈(栈2)是否存在待删除的元素
// 不存在则将添加栈(栈1)的元素出栈到栈2中
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
// 再次判断栈2是否为空,因为上一个判断后,可能栈1的元素也为空
// 也就是,此时“队列”中不存在元素,直接返回-1
// 否则,直接将栈2pop一个元素,再返回即可
if(stack2.isEmpty()) return -1;
else{
int res = stack2.pop();
return res;
}
}
}