代码随想录训练营第十天|232.用栈实现队列,225. 用队列实现栈

这篇博客介绍了如何利用栈和队列这两种数据结构来实现队列和栈的功能。在LeetCode上的两个问题中,作者分别展示了如何用栈模拟队列(232题)和用队列模拟栈(225题)。通过内部的转换操作,这两个数据结构可以互相补充,完成原本不属于它们的操作,如栈的出队和队列的进栈。
摘要由CSDN通过智能技术生成

232. 用栈实现队列 - 力扣(Leetcode)

参照题解,重用pop

class MyQueue {
public:
    stack<int> in;
    stack<int> out;
    MyQueue() {

    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        if(out.empty())
        {
            while(!in.empty())
            {
                out.push(in.top());
                in.pop();
            }
        }
        int res=out.top();
        out.pop();
        return res;
    }
    
    int peek() {
        int res=this->pop();
        out.push(res);
        return res;
    }
    
    bool empty() {
        return (in.empty()&&out.empty());
    }
};

225. 用队列实现栈 - 力扣(Leetcode) 

 

class MyStack {
public:
    queue<int>que;
    MyStack() {

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        int size=que.size();
        size--;
        while(size--)
        {
            que.push(que.front());
            que.pop();
        }
        int res=que.front();
        que.pop();
        return res;
    }
    
    int top() {
        int res=que.back();
        return res;
    }
    
    bool empty() {
        return que.empty();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值