题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解决思路:
- Stack1负责入栈
- Stack2负责出栈
- push ,pop方法
- 常规解法就是这样,网上没见到其他解法
public class Main5 {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
if(!stack2.isEmpty()){
swap(stack1, stack2);
}
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty()){
swap(stack2, stack1);
}
return stack2.pop();
}
public void swap (Stack<Integer>s1,Stack<Integer>s2){
if(s1==null||s2==null){
return ;
}
while(!s2.isEmpty()){
s1.push(s2.pop());
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
}
}