225. Implement Stack using Queues

Implement the following operations of a stack using queues.

1.push(x) – Push element x onto stack.
2.pop() – Removes the element on top of the stack.
3.top() – Get the top element.
4.empty() – Return whether the stack is empty.

方法一:基本思路
跟之前那道反过来的题几乎一样,Implement Queue using Stack, 也就是按照stack的顺序在queue中强行排列,简单直接。

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        queue<int> temp;
        while (!q.empty()) { //借用temp把queue里新push的值一直调到最顶端
            temp.push(q.front());
            q.pop();
        }
        q.push(x);
        while (!temp.empty()) {
            q.push(temp.front());
            temp.pop();
        }
    }

    // Removes the element on top of the stack.
    void pop() {
        q.pop();
    }

    // Get the top element.
    int top() {
        return q.front();
    }

    // Return whether the stack is empty.
    bool empty() {
        return q.empty();
    }

private:
    queue<int> q;
};

方法二:
换个新思路,方法一增加了push的复杂度。方法二增加了top, pop的复杂度,降低了push。

class Stack {
public:
    // Push element x onto stack.
    void push(int x) {
        while (!q2.empty()) {
            q1.push(q2.front());
            q2.pop();
        }
        q2.push(x);//保持q2中只有一个元素,就是新增的元素。
    }

    // Removes the element on top of the stack.
    void pop() {
        top();
        q2.pop();
    }

    // Get the top element.
    int top() {
        if (q2.empty()) {
            for (int i = 0; i < q1.size() - 1; i++) {
                q1.push(q1.front());
                q1.pop();
            }
            q2.push(q1.front());
            q1.pop();
        }
        return q2.front(); //q2代表栈顶的元素,如果q2没有,则要在q1最下面把那个元素挑出来放进q2
    }

    // Return whether the stack is empty.
    bool empty() {
        return q1.empty() && q2.empty();
    }

private:
    queue<int> q1, q2;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值