用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
我们都知道:
栈:先进后出
队列:先进先出
现在要使用两个栈模拟队列 实现先进先出
代码说明:
用stack1先存放入队的数,待要出队的时候,把stack1全部弹出到stack2,则stack2中的数据的出栈的顺序就和队列一样。但是必须要把stack2中的所有弹出之后再向stack2里面压入栈中。
example:PUSH1 PUSH2 PUSH3 POP POP PUSH4 POP PUSH5 POP POP
部分代码:
package com.xaut.jianzhioffer;
import java.util.Stack;
/*
* 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
* 栈:先进后出
* 队列:先进先出
* */
public class Solution_Stack {
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()){
return stack2.pop();
}
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}//现在stack1是空的
return stack2.pop();
}
}