力扣 剑指 Offer 09. 用两个栈实现队列 C++

解题思路:用两个栈stack1进数据stack2出数据,出的时候如果stack2为空,stack1不为空,则将stack1中的数据全部导入stack2中

代码:

 

class CQueue {
    stack stack1,stack2;
public:
    CQueue() {
        while(!stack1.empty()){
            stack1.pop();
        }
        while(!stack2.empty()){
            stack2.pop();
        }
    }
    
    void appendTail(int value) {
        stack1.push(value);
    }
    
    int deleteHead() {
        if(!stack1.empty()&&stack2.empty()){
          while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
          }
        }
        if(!stack2.empty()){
            int t=stack2.top();
            stack2.pop();
            return t;
        }
        return -1;
    }
};

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

你可能感兴趣的:(力扣,面试知识点,leetcode,c++,算法)