题目描述
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。
算是剑指offer的基中的基础题吧
解题思路
in 栈用来处理入栈(push)操作,out 栈用来处理出栈(pop)操作。一个元素进入 in 栈之后,出栈的顺序被反转。当元素要出栈时,需要先进入 out 栈,此时元素出栈顺序再一次被反转,因此出栈顺序就和最开始入栈顺序是相同的,先进入的元素先退出,这就是队列的顺序。
在栈中输入1 2 3
深度截图_选择区域_20190508094036.png
难点在于在输出前要先判断 s1 s2是否为空
import java.util.Stack;
public class Test {
public static void main(String[] args) {
Test test=new Test();
for (int i=0;i<5;i++){
test.push(i);
}
try {
test.pop();
System.out.println(test.pop());
} catch (Exception e) {
e.printStackTrace();
}
}
Stack<Integer> in = new Stack<Integer>();
Stack<Integer> out = new Stack<Integer>();
public void push(int node) {
in.push(node);
}
public int pop() throws Exception {
if (out.isEmpty())
while (!in.isEmpty())
out.push(in.pop());
if (out.isEmpty())
throw new Exception("queue is empty");
return out.pop();
}
}
```