leetcode 225 Implement Stack using Queues

1. 问题描述

  用队列来模拟栈的操作。实现如下栈操作:
  

  • push(x) 将元素x入栈。
  • pop() 出栈。
  • top() 获取栈顶元素。
  • empty() 判断是否为空。

  注意:只能用队列的标准操作,队头取元素,队尾插入元素,获取队列的大小,以及队列是否为空。


2 方法和思路

  可以用两个队列q1和q2来实现栈的操作,设q2为辅助队列。
  

  • 入栈时将元素都存入q1队列中。
  • 出栈时将q1中前n-1个元素放入q2队列,然后pop出q1的最后一个元素,最后将q2队列中的元素在放回到q1中。
  • 获取栈顶元素思路类似,只不过q1最后一个元素返回后,将其入q2,然后再将q2中所有元素放回到q1队列中,恢复原样。
  • 判断栈是否为空直接判断q1队列是否为空即可。

      C++代码如下:
      

class Stack {
    private:
    queue<int> q1;
    queue<int> q2;
public:
    // Push element x onto stack.
    void push(int x) {
        q1.push(x);

    }

    // Removes the element on top of the stack.
    void pop() {
        int n = q1.size();
        for(int i = 0; i < n -1; i++)
        {
            q2.push(q1.front());
            q1.pop();
        }
        q1.pop();

        while(!q2.empty())
        {
            q1.push(q2.front());
            q2.pop();
        }             
    }

    // Get the top element.
    int top() {
        int re,n = q1.size();
        for(int i = 0; i < n -1; i++)
        {
            q2.push(q1.front());
            q1.pop();
        }
        re = q1.front();

        q2.push(q1.front());
        q1.pop();

        while(!q2.empty())
        {
            q1.push(q2.front());
            q2.pop();
        }       
        return re;
    }

    // Return whether the stack is empty.
    bool empty() {
        return q1.empty();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值