题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
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
stack1.add(node);
}
public int pop() {//出队操作
if(stack2.isEmpty()){//stack2为空
while(!stack1.isEmpty()){//stack1非空,将其中的元素弹出,然后压入stack2
stack2.add(stack1.pop());
}
}
return stack2.pop();//stack2非空,弹出其中元素
}
}