题目
用两个栈来实现一个队列,使用n个元素来完成 n 次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
题解
stack1用来进,stack2用来出,当需要pop的时候:若stack2为空,则将stack1的倒装放入stack2,否则,直接stack2.pop().
代码
import java.util.Stack;
public class queens {
public static Stack<Integer> stack1 = new Stack<Integer>();
public static Stack<Integer> stack2 = new Stack<Integer>();
public static void push(int node) {
stack1.push(node);
}
public static int pop() {
if (!stack2.empty()){
return stack2.pop();
}
while(!stack1.empty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
public static void main(String[] args) {
push(1);push(2);
System.out.println(pop());
}
}