码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 232. 用栈实现队列

时间:2020-05-13 23:34:21      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:out   ret   https   problem   using   public   tst   void   获取   

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. 用栈实现队列

标签:out   ret   https   problem   using   public   tst   void   获取   

原文地址:https://www.cnblogs.com/jianzha/p/12885402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!