题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
代码
import java.util.Stack;
public class TestList2 {
static Stack<Integer> stack1 = new Stack<Integer>();
static Stack<Integer> stack2 = new Stack<Integer>();
public static void push1(int node) {
stack1.push(node);
}
public static int pop1() {
int n;
while(!stack1.isEmpty())
stack2.push(stack1.pop());
n=stack2.pop();
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return n;
}
public static void main(String[] args) {
push1(1);
push1(2);
push1(3);
System.out.println(pop1());
System.out.println(pop1());
push1(4);
System.out.println(pop1());
push1(5);
System.out.println(pop1());
System.out.println(pop1());
}
}