代码随想录算法训练营第十天|LeetCode232、LeetCode225

leetcode232

题目:

解法:

class MyQueue {
public:
    stack<int> scin;
    stack<int> scout;
    MyQueue() {
        
    }
    
    void push(int x) {
        scin.push(x);
    }
    
    int pop() {
        if(scout.empty())
        {
            while(!scin.empty())
            {
            scout.push(scin.top());
            scin.pop();
            }
        }
        int top = scout.top();
        scout.pop();
        return top;
    }
    
    int peek() {
        if(scout.empty())
        {
            while(!scin.empty())
            {
            scout.push(scin.top());
            scin.pop();
            }
        }
        return scout.top();
    }
    
    bool empty() {
        if(scout.empty()&&scin.empty())
        return true;
        else
        return false;
    }
};

 答案:(存在一个复用)

 /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

leetcode225:

题目:

 

 两个队列实现:

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

    }
    
    void push(int x) { 
        scin.push(x);
    }
    
    int pop() {
        while(!scout.empty())
        {
            scout.pop();
        }
        int size = scin.size();
        size--;
        while(size--)
        {
            scout.push(scin.front());
            scin.pop();
        }
        int out = scin.front();
        scin.pop();
        while(!scout.empty())
        {
            scin.push(scout.front());
            scout.pop();
        }
        return out;
    }
    
    int top() {
        return  scin.back();
    }
    
    bool empty() {
        if(scin.empty())
        return true;
        else
        return false;
    }
};

一个队列实现:

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

    }
    
    void push(int x) { 
        scin.push(x);
    }
    
    int pop() {
        int size = scin.size();
        size--;
        while(size--)
        {
            scin.push(scin.front());
            scin.pop();
        }
        int out = scin.front();
        scin.pop();
        return out;
    }
    
    int top() {
        return  scin.back();
    }
    
    bool empty() {
        if(scin.empty())
        return true;
        else
        return false;
    }
};

感悟:

要好好学习一下栈和队列的定义,掌握并使用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值