用两个栈实现队列
代码
public class Problem02_TwoStacksImplementQueue {
public static class myQueue{
Stack<Integer> stack1;
Stack<Integer> stack2;
public myQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void add(Integer newNum){
stack1.push(newNum);
}
public Integer poll(){
if(stack1.isEmpty() && stack2.isEmpty()){
throw new RuntimeException("Queue is Empty");
}else if(stack2.isEmpty()){
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public Integer peek(){
if(stack1.isEmpty() && stack2.isEmpty()){
throw new RuntimeException("Queue is Empty");
}else if(stack2.isEmpty()){
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
}
}
刷题
leetcode-cn.com/problems/yo…
精选题解
直通BAT算法精讲