难度 简单
和昨天的队列实现栈类似,昨天用队列实现栈的时候没有在入栈的时候处理而是在出栈时候处理,很麻烦。今天吸取教训在push的时候进行处理。
/** Initialize your data structure here. */
Stack<Integer> mStack = new Stack<Integer>();
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
Stack<Integer> tempS = new Stack<Integer>();
while(!mStack.isEmpty()){
tempS.push(mStack.pop());
}
mStack.push(x);
while(!tempS.isEmpty()){
mStack.push(tempS.pop());
}
tempS = null;
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return mStack.pop();
}
/** Get the front element. */
public int peek() {
return mStack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return mStack.isEmpty();
}