当前位置:网站首页>剑指 Offer 09. 用两个栈实现队列

剑指 Offer 09. 用两个栈实现队列

2022-07-05 08:16:00 程序员·小李

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

示例 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]

示例 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]

提示:

1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用

思路:

1. 一个插入栈,一个输出栈。插入数据时,往插入栈中写。

2. 输出数据时,优先从输出栈弹出,如果输出栈中不存在,则依次从输入栈中压入。

class CQueue {

    Stack<Integer> pushStack = new Stack<Integer>();
    Stack<Integer> popStack = new Stack<Integer>();
    public CQueue() {

    }
    
    public void appendTail(int value) {
        pushStack.push(value);
    }
    
    public int deleteHead() {
        if (popStack.empty()){
            while (!pushStack.empty()){
                popStack.push(pushStack.pop());
            }
        }

        if (popStack.empty()){
            return -1;
        }
        return popStack.pop();
    }
}

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

原网站

版权声明
本文为[程序员·小李]所创,转载请带上原文链接,感谢
https://everspringlee.blog.csdn.net/article/details/125610801