代码:
package 栈;
import java.util.Stack;
/**_232_用栈实现队列
* url: https://leetcode-cn.com/problems/implement-queue-using-stacks/
**/
public class _232_用栈实现队列 {
private Stack<Integer> inStack;
private Stack<Integer> outStack;
/** Initialize your data structure here. */
public _232_用栈实现队列() {
inStack = new Stack<>();
outStack = new Stack<>();
}
/** Push element x to the back of queue. 入队*/
public void push(int x) {
inStack.push(x);
}
/** Removes the element from in front of queue and returns that element.出队 */
public int pop() {
checkOutStack();
return outStack.pop();
}
/** Get the front element.队头 */
public int peek() {
checkOutStack();
//返回栈顶元素
return outStack.peek();
}
/** Returns whether the queue is empty.是否为空 */
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
private void checkOutStack() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}
}
网友评论