解题思路:栈是先进后出,队列是先进先出,有两个栈:栈1,栈2,可以先把栈1的元素弹出放入到栈2中,然后在弹出栈2的元素,这样就实现了先进先出。如: 依次输入到栈1的元素为a,b,c;栈1从顶到底:c,b,a;栈1弹出的元素放入栈2中,则栈2从顶到底为:a,b,c;实现了队列的先进先出。
代码如下:
import java.util.Stack;
public class TestStack {
Stack<Integer> stack1=new Stack<Integer>();
Stack<Integer> stack2=new Stack<Integer>();
public void push(int node) {
stack1.push(node); //向栈1中放入元素
}
public int pop() {
if(stack2.size()<=0) { //判断栈2中为空
while(stack1.size()>0) {
stack2.push(stack1.pop()); //将栈1弹出的元素放入栈2中
}
if(stack2.isEmpty()) {
try {
throw new Exception();
}catch(Exception e) {
e.printStackTrace();
}
}
}
return (int) stack2.pop(); //然后弹栈2
}
public static void main(String[] args) {
TestStack s=new TestStack();
s.push(23);
s.push(24);
s.push(45);
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
}
输出结果:
23
24
45