剑指 Offer ------------ 用两个栈实现队列

在这里插入图片描述

思路:
这道题的话,就是用栈的思想去做,一个栈用来进数,然后当要出数字的时候,只需要看看另外一个栈有没有数字,如果没有的话,就把栈1的数字放进栈2,此时栈2就相当于是队列中放置的元素。

代码:

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();
 */

猜你喜欢

转载自blog.csdn.net/weixin_43743711/article/details/115051672
今日推荐