学习笔记23 stack和queue

news2024/9/23 11:27:45

一、stack概念

stack是一种按先进后出方法存放和取出数据的数据结构

java提供了一个stack类,其中有以下几种方法:

看个例子:

import java.util.*;

/**
 * This program demonstrates the java.util.Stack class.
 */

public class StackDemo1 {
    public static void main(String[] args) {
        // Create a stack of strings and add some names
        Stack<String> stack = new Stack<>();
        String[] names = {"Al", "Bob", "Carol"};
        System.out.println("Pushing onto the stack the names:");
        System.out.println("Al Bob Carol");
        for (String s : names)
            stack.push(s);

        // Now pop and print everything on the stack
        String message = "Popping and printing all stack values:";
        System.out.println(message);
        while (!stack.empty())
            System.out.print(stack.pop() + " ");
    }
}
Pushing onto the stack the names:
Al Bob Carol
Popping and printing all stack values:
Carol Bob Al

 stack类不接受primitive data type,所以如果要存int,要转化为integer。

当然,如果你把primitive data type存入stack,java会自动box。

二、用array自己实现stack

public class ArrayStack {
    private int[] s; // Holds stack elements
    private int top; // Stack top pointer

    /**
     * Constructor.
     * @param capacity The capacity of the stack.
     */
    public ArrayStack(int capacity) {
        s = new int[capacity];
        top = 0;
    }

    /**
     * The empty method checks for an empty stack.
     * @return true if stack is empty.
     */
    public boolean empty() {
        return top == 0;
    }

    /**
     * The push method pushes a value onto the stack.
     * @param x The value to push onto the stack.
     * @exception StackOverflowException When the stack is full.
     */
    public void push(int x) {
        if (top == s.length)
            throw new StackOverflowException();
        else {
            s[top] = x;
            top++;
        }
    }

    /**
     * The pop method pops a value off the stack.
     * @return The value popped.
     * @exception EmptyStackException When the stack is empty.
     */
    public int pop() {
        if (empty())
            throw new EmptyStackException();
        else {
            top--;
            return s[top];
        }
    }

    /**
     * The peek method returns the value at the top of the stack.
     * @return value at top of the stack.
     * @exception EmptyStackException When the stack is empty.
     */
    int peek() {
        if (empty())
            throw new EmptyStackException();
        else {
            return s[top-1];
        }
    }
}

注意,我们需要自己实现两个异常类EmptyStackException StackOverFlowException

三、用linkedlist实现的stack

class LinkedStack {
    /**
     * The Node class is used to implement the linked list.
     */
    private class Node {
        String value;
        Node next;
        Node(String val, Node n) {
            value = val;
            next = n;
        }
    }

    private Node top = null; // Top of the stack

    /**
     * The empty method checks for an empty stack.
     * @return true if stack is empty, false otherwise.
     */
    public boolean empty() {
        return top == null;
    }

    /**
     * The push method adds a new item to the stack.
     * @param s The item to be pushed onto the stack.
     */
    public void push(String s) {
        top = new Node(s, top);
    }

    /**
     * The Pop method removes the value at the top of the stack.
     * @return The value at the top of the stack.
     * @exception EmptyStackException When the stack is empty.
     */
    public String pop() {
        if (empty())
            throw new EmptyStackException();
        else {
            String retValue = top.value;
            top = top.next;
            return retValue;
        }
    }

    /**
     * The peek method returns the top value on the stack.
     * @return The value at the top of the stack.
     * @exception EmptyStackException When the stack is empty.
     */
    public String peek() {
        if (empty())
            throw new EmptyStackException();
        else
            return top.value;
    }

    /**
     * The toString method computes a string representation of the contents of the stack.
     * @return The string representation of the stack contents.
     */
    public String toString() {
        StringBuilder sBuilder = new StringBuilder();
        Node p = top;
        while (p != null) {
            sBuilder.append(p.value);
            p = p.next;
            if (p != null)
                sBuilder.append("\n");
        }
        return sBuilder.toString();
    }
}

四、queue概念

queue是一种按先进先出方法存放和取出数据的数据结构

它应该包括如下方法:

enqueue ( x ): add a new item x to the rear of the queue
dequeue ( ): remove and return the item at the front of the queue
empty ( ): check if the queue is empty
peek ( ): return, but do not remove, the item at the front of the queue

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/818202.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Android 创建 Gradle Task 自动打包并上传至蒲公英

前言 Android 项目日常开发过程中&#xff0c;经常需要打包给到非开发人员验收或调试&#xff0c;例如测试阶段&#xff0c;就要经常基于测试服务器地址&#xff0c;打包安装包&#xff0c;给到组内测试人员进行测试&#xff0c;并且 BUG 修复完成之后也需要再次打包给到测试人…

极验4代滑块验证码破解(补环境直接强暴式拿下)

目录 前言一、分析二、验证总结借鉴 前言 极验第四代好像简单了特别多&#xff0c;没有什么技巧&#xff0c;环境党直接5分钟拿下。 网址: aHR0cHM6Ly93d3cuZ2VldGVzdC5jb20vYWRhcHRpdmUtY2FwdGNoYS1kZW1v 一、分析 直接去它官网&#xff0c;滑动滑块打开控制台瞅瞅 可以看…

Flask学习笔记_异步论坛(四)

Flask学习笔记_异步论坛&#xff08;四&#xff09; 1.配置和数据库链接1.exts.py里面实例化sqlalchemy数据库2.config.py配置app和数据库信息3.app.py导入exts和config并初始化到app上 2.创建用户模型并映射到数据库1.models/auth.py创建用户模型2.app.py导入模型并用flask-mi…

解决Debian10乱码以及远程连接ssh的问题

文章目录 解决Debian10乱码Debian10配置ssh 解决Debian10乱码 下载locales apt-get install locales配置语言 dpkg-reconfigure locales输入上述命令后会进入到以下页面【空格为选中&#xff0c;回车下一个页面】 在这个页面里我们按空格选中如图的选项&#xff0c;然后回…

安科瑞智慧空开微型断路器在银行的应用-安科瑞黄安南

应用场景 智能微型断路器与智能网关组合应用于末端回路 功能 1.计量功能&#xff1a;实时上报电压、电流、功率、电能、漏电、温度、频率等电参量&#xff1b; 2.报警功能&#xff1a;过压报警、欠压报警、过流报警、过载报警、漏电报警、超温报警、三相电缺相报警&#xff…

Jetson Docker 编译 FFmpeg 支持硬解nvmpi和cuvid

0 设备和docker信息 设备为NVIDIA Jetson Xavier NX&#xff0c;jetpack版本为 5.1.1 [L4T 35.3.1] 使用的docker镜像为nvcr.io/nvidia/l4t-ml:r35.2.1-py3,详见https://catalog.ngc.nvidia.com/orgs/nvidia/containers/l4t-ml 使用下列命令拉取镜像: sudo docker pull nvcr…

windows查看 jar包进程号指令

1 打开cmd 2 : 9898 jar包对应的端口号 netstat -aon|findstr 9898 3 &#xff1a;打开任务管理器 根据搜索出的23700 找到对应进程

【C++】STL——vector的模拟实现、常用构造函数、迭代器、运算符重载、扩容函数、增删查改

文章目录 1.模拟实现vector1.1构造函数1.2迭代器1.3运算符重载1.4扩容函数1.5增删查改 1.模拟实现vector vector使用文章 1.1构造函数 析构函数 在C中&#xff0c;vector是一个动态数组容器&#xff0c;可以根据需要自动调整大小。vector类提供了几个不同的构造函数来创建和初…

gradle项目上传项目依赖到远程仓库

gradle项目上传项目依赖到远程仓库 第一步&#xff1a;在需要上传的项目的bulid.gradle下添加maven插件&#xff0c;并配置连接远程仓库的信息以及项目的三要素信息&#xff0c;如下所示 dependencies {implementation org.mapstruct:mapstruct:1.4.2.Final } apply plugin: …

Linux - make/Makefifile

0.背景 会不会写makefile&#xff0c;从一个侧面说明了一个人是否具备完成大型工程的能力 一个工程中的源文件不计数&#xff0c;其按类型、功能、模块分别放在若干个目录中&#xff0c;makefile定义了一系列的规则来指定&#xff0c;哪些文件需要先编译&#xff0c;哪些文件需…

【Spring】Spring之循环依赖底层源码解析

什么是循环依赖 A依赖了B&#xff0c;B依赖了A。 示例&#xff1a; // A依赖了B class A{public B b; }// B依赖了A class B{public A a; }其实&#xff0c;循环依赖并不是问题&#xff0c;因为对象之间相互依赖是很正常的事情。示例&#xff1a; A a new A(); B b new B…

5分钟快手入门laravel邮件通知

第一步&#xff1a; 生成一个邮件发送对象 php artisan make:mail TestMail 第二步&#xff1a; 编辑.env 添加/修改&#xff08;没有的key则添加&#xff09; MAIL_DRIVERsmtp MAIL_HOSTsmtp.163.com &#xff08;这里用163邮箱&#xff09; MAIL_PORT25 &#xff08;163邮箱…

Bug记录: CUDA error_ device-side assert triggered

Bug记录&#xff1a; CUDA error: device-side assert triggered 在接触AIGC算法的过程中偶尔会遇到这样的bug&#xff1a;RuntimeError: CUDA error: device-side assert triggered return torch._C._cuda_synchronize() RuntimeError: CUDA error: device-side assert trig…

Qt实现引导界面UITour

介绍 最近做了一款键鼠自动化&#xff0c;想第一次安装打开后搞一个引导界面&#xff0c;找了好多资料没啥参考&#xff0c;偶然发现qt有引导界面如下图。 Qt整挺好&#xff0c;但是未找到源码&#xff0c;真的不想手撸&#xff0c;无奈实在找不到&#xff0c;下图是仿照qt实现…

在Vue中使用深度选择器定制Element Plus组件样式

介绍&#xff1a; 在Vue.js开发中&#xff0c;我们经常使用Element Plus作为UI组件库&#xff0c;它提供了丰富的组件供我们使用。然而&#xff0c;有时候我们希望对Element Plus的组件样式进行一些定制&#xff0c;比如调整字体大小、改变颜色等。在这篇博客中&#xff0c;我…

【GitOps系列】如何实施金丝雀发布?

文章目录 前言金丝雀发布概述金丝雀实战创建生产环境 部署金丝雀环境配置金丝雀策略金丝雀发布自动化创建 Rollout 对象创建 Service 和 Ingress 对象访问生产环境金丝雀发布自动化 访问 Argo Rollout Dashboard自动化原理结语 前言 蓝绿发布是一种通过资源冗余来换取回滚效率的…

关于jar文件反编译

最近在搞tck测试&#xff0c;想要将其日志转换成apdu脚本&#xff0c;结果出现默认输出最大长度不足&#xff0c;输出被省略现象。 软件log出现的错误信息 ... Output overflow: JavaTest Harness has limited the test output to the text to that at the beginning and the…

stable-diffusion-webui 启动服务,卡在浏览器loading中, 重定向解决

最新的code&#xff0c;按步骤安装&#xff0c;趟完pip和github的坑&#xff0c;终于启动服务 然后悲催的卡在浏览器这一步&#xff0c;一直在loading&#xff0c;折腾一下午&#xff0c;尝试可能有效的步骤&#xff0c;也许最后一步才有用&#xff1a; 1. 启动IIS服务 2. 配…

Java课题笔记~Maven基础

2、Maven 基础 2.1 Maven安装与配置 下载安装 配置&#xff1a;修改安装目录/conf/settings.xml 本地仓库&#xff1a;存放的是下载的jar包 中央仓库&#xff1a;要从哪个网站去下载jar包 - 阿里云的仓库 2.2 创建Maven项目

爬虫006_python中的运算符_算术运算符_赋值运算符_复合赋值运算符_比较运算符_逻辑运算符_逻辑运算符性能提升---python工作笔记024

首先看加减乘除 然后看这里的 // 是取整数部分,不是四舍五入 然后%这个是取余数 然后**是,几次方那种 指数