当前位置: 首页 > news >正文

【一起学数据结构与算法】深度学习栈

目录

  • 一、什么是栈?
  • 二、怎么使用栈?
    • 2.1 入栈 - push()
    • 2.2 判空 - empty()
    • 2.3 出栈 - pop()
    • 2.4 获取栈顶元素 - peek()
    • 2.5 获取栈中有效元素个数 - size()
  • 三、栈的模拟实现
    • 3.1 push
    • 3.2 isEmpty
    • 3.3 pop
    • 3.4 peek
    • 3.5 MyStack.java
  • 四、经典题
    • 4.1 有效的括号
    • 4.2 逆波兰表达式求值

一、什么是栈?

栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据在栈顶。

在这里插入图片描述

二、怎么使用栈?

栈的基本操作主要有:判空、判满、取栈顶元素、在栈顶进行插入和删除。在栈顶插入元素称为入栈,在栈顶删除元素称为出栈。

2.1 入栈 - push()

        Stack<Integer> s1 = new Stack<>();
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        System.out.println(s1);

在这里插入图片描述

2.2 判空 - empty()

        Stack<Integer> s1 = new Stack<>();
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        System.out.println(s1.empty());

在这里插入图片描述

2.3 出栈 - pop()

      Stack<Integer> s1 = new Stack<>();
	  s1.push(1);
      s1.push(2);
      s1.push(3);
      s1.push(4);
      System.out.println(s1);
      s1.pop();
      System.out.println(s1);

在这里插入图片描述

2.4 获取栈顶元素 - peek()

        Stack<Integer> s1 = new Stack<>();
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        System.out.println(s1);
        s1.peek();
        System.out.println(s1);
        System.out.println(s1.peek());

在这里插入图片描述

2.5 获取栈中有效元素个数 - size()

        Stack<Integer> s1 = new Stack<>();
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        System.out.println(s1.size());

在这里插入图片描述

三、栈的模拟实现

3.1 push

	public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    public void push(int val) {
        if (isFull()) {
            //扩容
            this.elem = Arrays.copyOf(this.elem,2*this.usedSize);
        }
        this.elem[this.usedSize] = val;
        this.usedSize++;
    }

3.2 isEmpty

	public boolean isEmpty() {
        return this.usedSize == 0;
    }

3.3 pop

	public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        int oldVal = this.elem[usedSize-1];
        this.usedSize--;
        return oldVal;
    }

3.4 peek

	public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        return this.elem[usedSize-1];
    }

3.5 MyStack.java

import java.lang.reflect.Array;
import java.util.Arrays;

@SuppressWarnings({"all"})
public class MyStack {
    public int[] elem;
    public int usedSize;

    public MyStack() {
        this.elem = new int[5];
    }

    public void push(int val) {
        if (isFull()) {
            //扩容
            this.elem = Arrays.copyOf(this.elem,2*this.usedSize);
        }
        this.elem[this.usedSize] = val;
        this.usedSize++;
    }

    public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        int oldVal = this.elem[usedSize-1];
        this.usedSize--;
        return oldVal;
    }

    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        return this.elem[usedSize-1];
    }

    public boolean isEmpty() {
        return this.usedSize == 0;
    }
}

四、经典题

4.1 有效的括号

在这里插入图片描述

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '(' || ch == '[' || ch == '{') {
                //如果是左括号 直接入栈
                stack.push(ch);
            } else {
                //遇到了右括号
                if (stack.empty()) {
                    System.out.println("右括号多");
                    return false;
                } 
                char top = stack.peek();//哪个左括号
                if (top == '(' && ch ==')' || top == '[' && ch ==']' || top == '{' && ch =='}') {
                    stack.pop();
                } else {
                    System.out.println("左右括号不匹配");
                    return false;
                }
            }
        }
        if (!stack.empty()) {
            System.out.println("左括号多");
            return false;
        }
        return true;
    }
}

4.2 逆波兰表达式求值

在这里插入图片描述

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            String val = tokens[i];
            if (!isOperation(val)) {
                stack.push(Integer.parseInt(val));
            } else {        
                int num2 = stack.pop();
                int num1 = stack.pop();
                switch (val) {
                    case "+":
                        stack.push(num1+num2);
                        break;
                    case "-":
                        stack.push(num1-num2);
                        break;
                    case "*":
                        stack.push(num1*num2);
                        break;
                    case "/":
                        stack.push(num1/num2);
                        break;
                }
            }
        }
        return stack.pop();
    }
    private boolean isOperation(String x) {
        if (x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/")) {
            return true;
        }
        return false;
    }
}

相关文章:

  • RHCSA知识点汇总
  • Python程序员,你还在用selenium吗?试试Playwright吧
  • STM32Fxx位带操作还不会?哲学三问让你实现位带自由(含位带操作核心代码)以LED与键盘为例
  • 大厂笔试面试总汇目录
  • ESP32 LVGL8.1 M5 Core2 + LVGL + IDF 详细的移植教程 (30)
  • 【论文阅读】Search-Based Testing Approach for Deep Reinforcement Learning Agents
  • c++版模板匹配与特征金字塔结构
  • 软件工程和Maven
  • 基于haarlike特征提取和Adaboost 的红绿灯/人行道检测识别matlab仿真
  • React的高阶组件详解
  • Python基础快速入门
  • FigDraw 22. SCI文章中绘图之核密度及山峦图 (ggridges)
  • 并联四足机器人项目开源教程(一)--- 机器人学导论的学习
  • 【CSS】笔记6-精灵图、字体图标
  • 秒懂如何使用SpringBoot+Junit4进行单元测试
  • input实现文字超出省略号功能
  • JavaScript函数式编程(一)
  • java小心机(3)| 浅析finalize()
  • Linux Process Manage
  • Redis字符串类型内部编码剖析
  • 闭包,sync使用细节
  • 从零开始在ubuntu上搭建node开发环境
  • 对象管理器(defineProperty)学习笔记
  • 理解IaaS, PaaS, SaaS等云模型 (Cloud Models)
  • 容器服务kubernetes弹性伸缩高级用法
  • 手写双向链表LinkedList的几个常用功能
  • 微信开源mars源码分析1—上层samples分析
  • 我的zsh配置, 2019最新方案
  • 字符串匹配基础上
  • 你对linux中grep命令知道多少?
  • 如何用纯 CSS 创作一个货车 loader
  • ​ubuntu下安装kvm虚拟机
  • # include “ “ 和 # include < >两者的区别
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • ( )的作用是将计算机中的信息传送给用户,计算机应用基础 吉大15春学期《计算机应用基础》在线作业二及答案...
  • (2)(2.10) LTM telemetry
  • (3)llvm ir转换过程
  • (C语言)编写程序将一个4×4的数组进行顺时针旋转90度后输出。
  • (C语言版)链表(三)——实现双向链表创建、删除、插入、释放内存等简单操作...
  • (html转换)StringEscapeUtils类的转义与反转义方法
  • (Oracle)SQL优化技巧(一):分页查询
  • (笔记)Kotlin——Android封装ViewBinding之二 优化
  • (紀錄)[ASP.NET MVC][jQuery]-2 純手工打造屬於自己的 jQuery GridView (含完整程式碼下載)...
  • (三)模仿学习-Action数据的模仿
  • (十一)图像的罗伯特梯度锐化
  • (转)淘淘商城系列——使用Spring来管理Redis单机版和集群版
  • (转)重识new
  • (轉貼) VS2005 快捷键 (初級) (.NET) (Visual Studio)
  • .NET C#版本和.NET版本以及VS版本的对应关系
  • .net core 6 集成和使用 mongodb
  • .NET Framework Client Profile - a Subset of the .NET Framework Redistribution
  • .net的socket示例
  • .Net下的签名与混淆
  • @JsonSerialize注解的使用
  • [ 云计算 | AWS 实践 ] 基于 Amazon S3 协议搭建个人云存储服务