232. 用栈实现队列(两个栈实现一个队列)_队列

232. 用栈实现队列(两个栈实现一个队列)_centos_02

class MyQueue {

Stack<Integer> inStack; //饱汉模式
Stack<Integer> outStack;

/** Initialize your data structure here. */
public MyQueue() {
inStack = new Stack();
outStack = new Stack();

}

private void checkOutStackIsEmpty(){ //检查第二个栈是否为空,为空就执行下面的操作
if (outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
}
/** 入队 */
public void push(int x) {
inStack.push(x);
}

/** 出队 */
public int pop() {
checkOutStackIsEmpty();
return outStack.pop();

}

/** 查看队头元素 */
public int peek() {
checkOutStackIsEmpty();
return outStack.peek();

}

/** 判断队列是否为空 */
public boolean empty() {
if (inStack.isEmpty() && outStack.isEmpty()) return true;
return false;
}

}

/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/