[LeetCode] 225. Implement Stack using Queues

225. Implement Stack using Queue (用两个队列实现一个栈)



1. 题目翻译

使用两个队列完成一个栈的下列功能

  • push(x) – 将x加入栈顶
  • pop() – 移除栈顶的元素。
  • peek() – 返回栈顶的元素。
  • empty() – 如果栈为空返回true。

注意:

  • 只能使用标准的队列操作–包括push,peek,pop,size和empty(C++ queue容器中的取队尾操作不能使用)。
  • 假设所有操作都是有效的(即不存在对空栈的pop和peek操作)。

2. 解题方法

与用两个栈实现队列不同的是,从一个对列将所有数据移到另一个队列,顺序是不会改变的。

对于插入操作来说,很简单。首先判断哪个队列已经存在元素就往该队列加入元素就可以。如果两个队列都为空,可以随意加入。

假设向栈中按序压入元素{1},{2},{3},我们将他们加入q1中。此时我们要将栈顶元素3移出。我们可以首先将元素{1},{2}移入队列q2中,然后将队列q1中剩余的最后一个元素,即{3}移除就可以。同理,接着移除元素{2}的时候,只要将q2中的除最后一个元素{2}以外的元素,这里只有{1}移到q1中,然后将{2}从q2删除即可。

3. 代码

//Runtime: 0ms
class MyStack {
private:
    queue<int> q1;
    queue<int> q2;
public:
    /** Initialize your data structure here. */
    MyStack() {

    }

    /** Push element x onto stack. */
    void push(int x) {
        if(!q2.empty()){
            q2.push(x);
        }else
            q1.push(x);
    }

    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int top;

        if(!q1.empty()){
            while(q1.size()>1){
                q2.push(q1.front());
                q1.pop();
            }   

            top = q1.front();
            q1.pop();
        }else if(!q2.empty()){
            while(q2.size()>1){
                q1.push(q2.front());
                q2.pop();
            }   

            top = q2.front();
            q2.pop();
        }
        return top;
    }

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

    /** Returns 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、付费专栏及课程。

余额充值