LeetCode 232. 用栈实现队列
Posted jianzha
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 232. 用栈实现队列相关的知识,希望对你有一定的参考价值。
import java.util.Stack;
/**
* 232. 用栈实现队列
* https://leetcode-cn.com/problems/implement-queue-using-stacks/
*/
public class _232_Implement_Queue_using_Stacks {
private Stack<Integer> inStack;
private Stack<Integer> outStack;
/** Initialize your data structure here. */
public _232_Implement_Queue_using_Stacks() {
inStack = new Stack<>();
outStack = new Stack<>();
}
/** 入队 */
public void push(int x) {
inStack.push(x);
}
/** 出队 */
public int pop() {
checkOutStack();
return outStack.pop();
}
/** 获取队头元素 */
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());
}
}
}
}
以上是关于LeetCode 232. 用栈实现队列的主要内容,如果未能解决你的问题,请参考以下文章