题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:
push操作就直接往stack1中push。
pop操作需要分类一下:如果stack2为空,那么需要将stack1中的数据转移到stack2中,然后在对stack2进行pop,
如果stack2不为空,直接pop就ok。
代码:
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.empty()){
return stack2.pop();
}else{
while(!stack1.empty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
}