1.题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
2.思路
栈的特性为先入后出,队列的特性为先入先出。可以用一个栈入栈来实现队列的Push操作,然后将该栈的元素出栈并入栈到另一个栈,然后第二个栈的出栈来实现队列的Pop操作。
3.代码
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()){//这里要保证stack2中的元素为空(包含全部出栈)后,才可入栈,否则相对顺序就会乱,不能实现队列的先进先出
while(!stack1.isEmpty())
stack2.push(stack1.pop());
}
return stack2.pop();
}
}