题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
分析:
1,两个栈,一个作为push栈,一个作为pop栈;
2,push时,栈1push时
3,pop时,保证两点:
(1),stack2必须保证为空;
(2),stack1向stack2弹进元素时,必须一次性全部弹完;
(3),stack2 pop出一个元素;
代码展示:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//保证pop时,stack2为空;
//保证pop时,一次性将stack1中的所有元素,都push进stack2
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty() && stack1.empty()){
throw new RuntimeException("Queue is empty");
}else if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
注:此题在剑指offer和左神书中均有出现;