剑指offer编程题
用两个栈来实现一个队列,完成队列的Push和Pop操作。
思路:由于队列是先进先出的,而栈是先进后出的,所以要用2个栈来实现队列的入队出队功能,队列的入队功能与栈的一样,出队时,先将第一个栈中的元素全部弹出,并倒入到第二个栈中,将第二个栈中栈顶元素弹出,并将stack2中剩下的元素倒回到stack1中,即实现一次出队操作
实现
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
stack1.push(node);
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
public int pop() {
return stack2.pop();
}
}