【leetcode】 225. Implement Stack using Queues

采用两个队列。

  • push:首先找到空的队列,将元素入栈,并将另一个队列的所有的元素依次入当前队列并清栈。保证后进先出
  • pop:  找到非空的那个队列,弹出一个元素
  • top:   找到非空的那个队列,top拿出一个元素
  • empty: 判断两个队列是否都是非空。
关键是push操作的理解。

/**
 * @author          johnsondu
 * @problem         Implement Stack using Queues
 * @url             https://leetcode.com/problems/implement-stack-using-queues/
 * @timeComlexity   O(n^2)
 * @spaceComplexity O(n)
 * @strategy        See code.
 */

class Stack {
public:
    queue<int> q1;
    queue<int> q2;
    // Push element x onto stack.
    void push(int x) {
        if(q1.empty()) {
            q1.push(x);
            while(!q2.empty()) {
                q1.push(q2.front());
                q2.pop();
            }
        }
        else {
            q2.push(x);
            while(!q1.empty()) {
                q2.push(q1.front());
                q1.pop();
            }
        }
    }

    // Removes the element on top of the stack.
    void pop() {
        if(!q1.empty()) {
            q1.pop();
        }
        else {
            if(!q2.empty()) q2.pop();
        }
    }

    // Get the top element.
    int top() {
        if(!q1.empty()) {
            return q1.front();
        }
        else {
            return q2.front();
        }
    }

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值