首页 > 其他 > 详细

9、用两个栈实现队列

时间:2021-04-22 09:10:52      阅读:20      评论:0      收藏:0      [点我收藏+]
class CQueue {
    private Stack<Integer> inStack;
    private Stack<Integer> outStack;
    private int size = 0;
    public CQueue() {
        inStack = new Stack<>();
        outStack = new Stack<>();
        size = 0;
    }


    public void appendTail(int value) {
        size++;
        inStack.push(value);
    }

    public int deleteHead() {
        if (size == 0){
           return -1;
        }else if (outStack.isEmpty()){
            moveElementFromInToOut();
        }
        size--;
        return outStack.pop();

    }

    private void moveElementFromInToOut() {
        while (!inStack.isEmpty()){
            outStack.push(inStack.pop());
        }
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */

9、用两个栈实现队列

原文:https://www.cnblogs.com/linyxBlog/p/14687298.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!