Eagle233-Blog

[Algorithms] LeetCode 232.用栈实现队列


Categories Algorithms StackAndQueue
Tags

284 Words   |   1 Minutes

来源:代码随想录

LeetCode 232.用栈实现队列

直观的方法

效率不高。

class MyQueue {
public:
    stack<int> in;
    stack<int> out;

    MyQueue() {
        
    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        while (!in.empty()) {
            out.push(in.top());
            in.pop();
        }
        int n = out.top();
        out.pop();
        while (!out.empty()) {
            in.push(out.top());
            out.pop();
        }
        return n;
    }
    
    int peek() {
        while (!in.empty()) {
            out.push(in.top());
            in.pop();
        }
        int n = out.top();
        while (!out.empty()) {
            in.push(out.top());
            out.pop();
        }
        return n;
    }
    
    bool empty() {
        if (in.empty()) {
            return true;
        }
        return false;
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

复用

在pop()中,为什么要判断out是空的?

class MyQueue {
public:
    stack<int> in;
    stack<int> out;

    MyQueue() {
        
    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        if (out.empty()) {
            while (!in.empty()) {
                out.push(in.top());
                in.pop();
            }
        }
        
        int a = out.top();
        out.pop();
        return a;
    }
    
    int peek() {
        int a = this->pop();
        out.push(a);
        return a;
    }
    
    bool empty() {
        if (out.empty() && in.empty()) {
            return true;
        }
        return false;
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */


Page views: Loading...  ·  Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号
Search