LeetCode第225题---用队列实现栈

LeetCode链接: link.

在这里插入图片描述
解题思路

  1. 不管底层用什么结构实现,永远保证数据先进后出的一个逻辑数据结构,即栈

  2. 借助队列实现栈,可以使用两个队列,也可以只是用一个队列,本解只借助一个队列即可

  3. 入栈,即把数据进行入队,为了保证栈的特性先进后出,因此需要在push方法中对入队之前的所有元素进行一次出 队入队操作,以保证所有数据达到先进后出的顺序

  4. 出栈,由于队列数据顺序已经调整,所以只需取队头元素即可

class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        int size = q.size();
        q.push(x);
        while(size--)
        {
            int temp = q.front();
            q.pop();
            q.push(temp);
        } 
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int popVal = q.front();
        q.pop();
        return popVal;
    }
    
    /** Get the top element. */
    int top() {
        return q.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }

    private:
        queue<int> q;
};

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值