代码随想录算法训练营第十天 | LeetCode 232、225


前言

LeetCode题目:LeetCode 232、225
Takeaway:栈和队列的基础知识,不涉及算法,主要是理解并且模拟。


一、LeetCode 232

没什么好说的,没有算法,全是模拟,理解什么是栈什么是队列就好。

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;

    MyQueue() {

    }
    
    void push(int x) {
        stIn.push(x);
    }
    
    int pop() {
        int num;
        while(stIn.size()!=0){
            num = stIn.top();
            stIn.pop();
            stOut.push(num);
        }
        int outNum = stOut.top();
        stOut.pop();
        while(stOut.size()!=0){
            num = stOut.top();
            stOut.pop();
            stIn.push(num);
        }
        return outNum;
    }
    
    // 逻辑和pop()几乎一模一样
    int peek() {
        int num;
        while(stIn.size()!=0){
            num = stIn.top();
            stIn.pop();
            stOut.push(num);
        }
        int outNum = stOut.top();
        while(stOut.size()!=0){
            num = stOut.top();
            stOut.pop();
            stIn.push(num);
        }
        return outNum;
    }
    
    bool empty() {
        return stIn.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

二、LeetCode 225

同上,全是模拟,唯一值得注意的是队列删除最后一个元素不一样。

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

    }
    
    void push(int x) {
        queIn.push(x);
    }
    
    int pop() {
        int num;
        // 这里是1,因为最后一个元素要删除
        while(queIn.size()!=1){
            num = queIn.front();
            queIn.pop();
            queOut.push(num);
        }
        int outNum = queIn.front();
        queIn.pop();
        // 注意这里是大小不能等于0!
        while(queOut.size()!=0){
            num = queOut.front();
            queOut.pop();
            queIn.push(num);
        }
        return outNum;
    }
    
    int top() {
        return queIn.back();
    }
    
    bool empty() {
        return queIn.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

总结

今天的题没有难度,全是模拟,主要是需要理解栈和队列的意义。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值