剑指offer 09 两个栈实现队列

 思路:

入队时,直接进到A中

出队时,看B是否为空,若不是空,直接从B弹出结果

否则,看A是否为空,如果为空,说明目前没有元素,返回-1

否则,将A中的元素逐个出栈,放到B中,弹出B栈顶元素,即为结果。

class CQueue {
public:
    stack<int>A,B;
    CQueue() {
    }
    
    void appendTail(int value) {

        A.push(value);
    }
    
    int deleteHead() {

        if(A.empty() && B.empty())
            return -1;
        if(B.empty()){
            while(!A.empty()){
                B.push(A.top());
                A.pop();
            }
        }
        int res = B.top();
        B.pop();
        return res;
    }
};


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

猜你喜欢

转载自blog.csdn.net/m0_38062470/article/details/114666870