其他分享
首页 > 其他分享> > 剑指 Offer 09. 用两个栈实现队列

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

作者:互联网

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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 次调用


解析:

  push的时候先赋值再++

  pop的时候先--再返回

class CQueue {
public:
    int st1[10010], st2[10010];
    int cnt1, cnt2;
    CQueue() {
        this->cnt1 = 0, this->cnt2 = 0;
    }
    
    void appendTail(int value) {
        st1[cnt1++] = value;
    }
    
    int deleteHead() {
        if(cnt2 != 0)
        {
            cnt2--;
            return st2[cnt2];
        }
        if(cnt1 == 0) return -1;
        while(cnt1)
        {
            cnt1--;
            st2[cnt2] = st1[cnt1];
            cnt2++;
        }
        cnt2--;
        return st2[cnt2];
    }
};

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

 

标签:deleteHead,appendTail,Offer,队列,CQueue,09,cnt2,cnt1,null
来源: https://www.cnblogs.com/WTSRUVF/p/16151662.html