10-用栈实现队列


代码:

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());
            }
        }
    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容