题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:第一个栈,功能作为入队列;第二个栈,功能作为出队列,如果为空,把stack1出栈 ,并进栈stack2, 如果不为空,直接出栈。
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 (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
if (stack2.isEmpty()) {
Exception e = new Exception("123");
try {
throw e;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
return stack2.pop();
}
}
扩展: 两个队列实现栈。
思路:队列为A,B。进栈,如果队列 A只有一个,直接出队列,否则将队列A中的元素,依次出队列并放入队列B,直到队列A中的元素留下一个,然后队列A出队列,再把队列B中的元素出队列依次放入队列A中。