两个栈实现队列
import java.util.Stack;
/**
* Create by ~JH~ on 2018/4/30
* 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
*/
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() {
//将stack1的元素移入stack2,输出stack2的栈顶元素就是第一个入队的元素
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int result=stack2.pop();
//再将stack2的元素重新移入stack1
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return result;
}
}