用栈实现队列
click here for leetcode detail
class MyQueue {
Stack<Integer> firstStack;
Stack<Integer> secondStack;
public MyQueue() {
firstStack = new Stack();
secondStack = new Stack();
}
public void push(int x) {
firstStack.push(x);
}
public int pop() {
if(empty()){
return -1;
}
//这里需要注意,两个栈同时利用,保证每组连续的push一次性进secondStack,
//secondeStack为空才进行下一组的firstSatck到secondStack
if(secondStack.empty()){
while(!firstStack.empty()){
secondStack.push(firstStack.pop());
}
}
return secondStack.pop();
}
public int peek() {
if(empty()){
return -1;
}
if(secondStack.empty()){
while(!firstStack.empty()){
secondStack.push(firstStack.pop());
}
}
return secondStack.peek();
}
public boolean empty() {
return firstStack.empty() && secondStack.empty();
}
}
网友评论