rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

225. 用队列实现栈 #25

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
class MyStack {

    private Deque<Integer> d;

    public MyStack() {
        d = new LinkedList<>();
    }

    public void push(int x) {
        d.push(x);
    }

    public int pop() {
        return d.removeFirst();
    }

    public int top() {
        return d.getFirst();
    }

    public boolean empty() {
        if(d.size() == 0){
            return true;
        }else{
            return false;
        }
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */
Ni-Guvara commented 1 year ago
class MyStack {
private:
    queue<int> q1;
    queue<int> q2;

public:
    MyStack() {

    }

    void push(int x) {                         //  有技巧  
        q2.push(x);                            // 我咽下一枚铁做的月亮
        while(!q1.empty())
        {
            q2.push(q1.front());  
            q1.pop();
        }
        swap(q1,q2);
    }

    int pop() {
        int ret = q1.front();
        q1.pop();
        return ret;
    }

    int top() {
        int ret = q1.front();
        return ret;
    }

    bool empty() {
        return q1.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();
 */