力扣刷题笔记 栈与队列篇

总结先放在前面:

栈和队列是可以互相转换使用的,其中两个栈可以实现一个队列,而一个队列就可以实现栈。
栈通常用来解决匹配问题,比如说NO.20. 有效的括号和NO.1047. 删除字符串中的所有相邻重复项以及NO.150. 逆波兰表达式求值
对于队列,应该通过 NO.239. 滑动窗口最大值 来学习单调队列(实际上由于C#不像C++或者java一样有方法可以获取队列的末尾值getLast()和removeLast()之类的方法,我们需要使用List来进行替代),这里主要是学习它的想法

解答栈与队列时的一些小技巧与注意点:

栈对于在遇到字符串以及一个有关于处理优先级顺序方面的题目很有用,比如说括号匹配,逆波兰表达式
队列需要学会单调队列的思想,NO.239. 滑动窗口最大值 主要提示了队列在窗口类题目的应用

题目实战

1.NO.232.用栈实现队列

在这里插入图片描述

public class MyQueue {
   

    Stack<int> st1=new Stack<int>(); //st1用来保存数据
    Stack<int> st2=new Stack<int>(); //st2用来保存顺序排好的数据
    /** Initialize your data structure here. */
    public MyQueue() {
   

    }
    
    /** Push element x to the back of queue. */
    public void Push(int x) {
    //
        st1.Push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int Pop() {
   
        while(st1.Count!=0){
   
            st2.Push(st1.Pop());
        }
        int tmp=st2.Pop();
        while(st2.Count!=0){
   
            st1.Push(st2.Pop());
        }
        return tmp;
    }
    
    /** Get the front element. */
    public int Peek() {
    //队列开头的元素,就是栈最底下的元素。
        while(st1.Count!=0){
       //把st1全部压到st2中,顺序就对了
            st2.Push(st1.Pop());
        }
        int tmp= st2.Peek();
        while(st2.Count!=0){
       //复原
            st1.Push(st2.Pop());
        }
        return tmp;
    }
    
    /** Returns whether the queue is empty. */
    public bool Empty() {
   
        if(st1.Count==0){
   
            return true;
        }
        return false;
    }
}

/**
 * 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();
 */

2.NO.225. 用队列实现栈

在这里插入图片描述
其实队列实现一个栈只需要知道队列里面有多少个元素就行了,通过不断地出和进来改变顺序

public class MyStack {
   
    Queue<int> que=new Queue<int>();
    int count=0; //count用来保存当前队列中元素的个数
    /** Initialize your data structure here. */
    public MyStack() {
   

    }
    
    /** Push element x onto stack. */
    public void Push(int x) {
   
        que.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值