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

这道题就是一个堆栈出,另一个堆栈进,来模拟一个队列。

class CQueue {
public:
    CQueue() {
        while (!stack1.empty()) stack1.pop();
        
        while (!stack2.empty()) stack2.pop();
    }

    void appendTail(int value) {
        stack1.push(value);
    }

    int deleteHead() {
        if (stack2.empty()) {
            while (!stack1.empty()) {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        
        if (stack2.empty()) return -1;
        else {
            int deleteItem = stack2.top();
            stack2.pop();
            return deleteItem;
        }
     }
private:
    stack<int> stack1, stack2;
};

猜你喜欢

转载自blog.csdn.net/jcl314159/article/details/119572457