代码随想录:用队列实现栈

代码随想录:用队列实现栈

class MyStack {
public:
    //pop就是拿队列的最后一个元素,只需要用另一个队列对现有队列遍历,拿到最后一个元素即可
    queue<int> target;
    MyStack() {
        
    }
    
    void push(int x) {
        target.push(x);
    }
    
    int pop() {
        int len = target.size();
        while(len>1){
            target.push(target.front());
            target.pop();
            len--;
        }
        int val = target.front();
        target.pop();
        return val;
    }
    
    int top() {
                int len = target.size();
        while(len>1){
            target.push(target.front());
            target.pop();
            len--;
        }
        int val = target.front();
        target.push(target.front());
        target.pop();
        return val;
    }
    
    bool empty() {
        return target.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
posted @ 2024-12-10 22:39  huigugu  阅读(11)  评论(0编辑  收藏  举报