question:
用两个栈来实现一个队列,完成队列的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.push(node);
}
public int pop() {
if(stack1.isEmpty()&&stack2.isEmpty()){
throw new RuntimeException("queue is empty"); //这也要学习一波
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}