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

仅供自己学习

思路:

需要定义两个栈st1,st2.第一次调用CQueue()时,可以用于清空两个栈。加入元素的函数直接加入进st1即可,对于删除函数,要先判断st2是否为空,如果不为空直接从st2弹出元素,如果为空就从st1一直加元素直到st1为空,如果st1为空,st2没有元素加进去,那么就返回-1即可。
代码:

class CQueue {
private:
    stack<int> st1;
    stack<int> st2;
public:
    CQueue() {
        while(!st1.empty()) st1.pop();
        while(!st2.empty()) st2.pop();
    }
    
    void appendTail(int value) {
        st1.push(value);
        return;
    }
    
    int deleteHead() {
        if(st2.empty()) {
            while(!st1.empty()){
            int temp=st1.top(); st1.pop();
            st2.push(temp);
            }
        }
        if(st2.empty()){
            return -1;
        }
        int det=st2.top();st2.pop();
        return det;
    }
};

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

插入时间复杂度为O(1),删除的话 因为每个数都是从st1移除加到st2中,所以也是O(1),只是每次st2空后 从st1加进来n个元素就需要O(n),但总体来看仍然是O(1)。
空间复杂度是O(n)因为用两个栈嘛

posted @ 2021-04-05 00:18  Mrsdwang  阅读(35)  评论(0编辑  收藏  举报