栈和队列经典OJ题

本文概述了如何用栈和队列数据结构解决LeetCode中的六个经典问题,包括用队列实现栈、用栈实现队列、括号匹配、逆波兰表达式、最小栈以及滑动窗口算法的应用。通过实例解析,展示了这些数据结构在算法中的实际运用和优化技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. LeetCode第225题—用队列实现栈

链接: https://leetcode-cn.com/problems/implement-stack-using-queues/
在这里插入图片描述
题解:用队列实现栈,其中只需要一个队列,核心在于想要队列是先入先出,而战则是后进的先出,所以要在push()这个接口处下功夫思考,在我插入的时候,我把原先的数据都拿出来在重新插入一次,这样此时队列头部的值就是最后一个入队的元素,就满足了栈的后进先出的原则

class MyStack {
   
public:
    MyStack() {
   

    }
    
    void push(int x) {
   
        int size = q.size();
        q.push(x);
        while(size--)
        {
   
            int tmp = q.front();
            q.pop();
            q.push(tmp);
        }
    }
    
    int pop() {
   
        int popVal = q.front();
        q.pop();
        return popVal;
    }
    
    int top() {
   
        return q.front();
    }
    
    bool empty() {
   
        return q.empty();
    }
    //使用队列来实现栈,只需要一个队列即可
private:
    queue<int> q;
};

2. LeetCode第232题—用栈实现队列

链接: https://leetcode-cn.com/problems/implement-queue-using-stacks/
在这里插入图片描述
st1就只负责入数据,st2负责将st1里面的元素进行颠倒以达到队列的性质

class MyQueue {
   
private:
    stack<int> st1;
    stack<int> st2;
public:
    MyQueue() {
   

    }
    //st1只负责入数据,st2负责将st1里面的元素进行颠倒以达到队列的性质
    void push(int x) {
   
        st1.push(x);
    }
    
    int pop() {
   
        int val;
        while(!st2.empty())
        {
   
            val = st2.top();
            st2.pop();
            return val;
        }
        while(!st1.empty())
        {
   
            val = st1.top();
            st1.pop();
            st2.push(val);
        }
        int TopVal = st2.top();
        st2.pop();
        return TopVal;
    }
    
    int peek() {
   
        int val;
        while(!st2.empty())
        {
   
            return st2.top();
        }
        while(!st1.empty())
        {
   
            val = st1.top();
            st1.pop();
            st2.push(val);
        }
        return st2.top();
    }
    
    bool empty() {
   
        return st1.empty() && st2.empty();
    }
};

3. LeetCode第20题—有效的括号

链接: https://leetcode-cn.com/problems/valid-parentheses/
在这里插入图片描述

class Solution {
   
public:
    //这道题就是典型的使用栈来解决的问题的,如果我们天真的就是去数左半边括号的数量然后再去数右半边括号的数量,这样的做法是不正确的,因为你看示例4就会发现
    //真正的做法是遇见左括号就入栈,当遇见右括号的时候就进行出栈,看是否能够进行匹配
    bool isValid(string s) {
   
        stack<char> st;
        for(int i = 0;i<s.size();++i)
        {
   
            if(s[i] == '(' || s[i] == 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值