Sword refers to Offer ------------ Implement queue with two stacks

Insert picture description here

Idea: This
question is to use the idea of ​​a stack to do it. One stack is used to enter the number, and then when you want to output a number, you only need to see if the other stack has a number, if not, put the stack 1 The number is put into stack 2, and stack 2 is equivalent to the element placed in the queue.

Code:

class CQueue {
    
    
public:
    CQueue() {
    
    
    }
    
    void appendTail(int value) {
    
    
        st1.push(value);
        return ;
    }
    
    int deleteHead() {
    
    
        if(st1.size()==0 && st2.size()==0  )  return -1;

        if(st2.size()){
    
    
            int t = st2.top();
            st2.pop();
            return t;
        }else{
    
    
            while(!st1.empty()){
    
    
                st2.push(st1.top());
                st1.pop();
            }
            int t = st2.top();
            st2.pop();
            return t;
        }
        return 0;
    }

private:
    stack<int> st1,st2;
};

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

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115051672