【数据结构】JavaScript栈实现

2023-11-02

栈是一种常见的数据结构,常用于app页面堆栈、括号匹配校验、中缀表达式转换、图的深度优先遍历等场景,本文参考java jdk源码,在JavaScript中实现这种数据结构。

一、栈的定义

栈是限定仅在表尾进行插入和删除操作的线性表。允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom),不含任何数据元素的栈称为空栈。栈又称为后进先出的线性表

image-20220127202810611

二、实现JavaScript栈

参考[java的Stack源码](# 四、附:java的Stack源码),我们通过定义JavaScript栈的基本方法:

  • 入栈(push)

  • 出栈(pop)

  • 返回栈顶元素值(peek)

  • 判断堆栈是否为空(empty)

  • 返回给定对象的位置(search)

  • 清空栈(clear) 等

并实现JavaScript源码如下

// 定义堆栈类
class Stack {

  constructor() {
    this._elementData = [];
  }

  // 入栈
  push(item) {
    this._elementData[this._elementData.length] = item;
  }

  // 出栈
  pop() {
    if (this._elementData.length) {
      this._elementData.splice(this._elementData.length - 1, 1);
      return true;
    } else {
      return false;
    }
  }

  // 返回栈顶元素值,若堆栈为空则返回null
  peek() {
    if (this._elementData.length) {
      return this._elementData[this._elementData.length - 1];
    } else {
      return null;
    }
  }

  // 判断堆栈是否为空
  empty() {
    return this._elementData.length === 0;
  }

  // 返回给定对象的位置
  search(item) {
    let i = this._elementData.lastIndexOf(item);
    if (i >= 0) {
      return this.size() - i;
    } else {
      return -1;
    }
  }

  // 获取堆栈元素个数
  size() {
    return this._elementData.length;
  }

  // 获取堆栈数据
  getData() {
    return this._elementData;
  }

  // 清空栈
  clear() {
    this._elementData = [];
  }
}

三、验证功能

const stack = new Stack();
stack.push('nodeA');
stack.push('nodeB');
stack.push('nodeC');
while (!stack.empty()) {
  console.log(stack.getData());
  stack.pop();
}

验证结果

image-20220127202810611

四、附:java的Stack源码

调用java的Stack

public class StackTest {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        stack.push("nodeA");
        stack.push("nodeB");
        stack.push("nodeC");
        while (!stack.isEmpty()){
            System.out.println(stack);
            stack.pop();
        }
    }
}
image-20220127202810611

java的Stack源码:

/*
 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.util;

/**
 * The <code>Stack</code> class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
 * operations that allow a vector to be treated as a stack. The usual
 * <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
 * method to <tt>peek</tt> at the top item on the stack, a method to test
 * for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
 * the stack for an item and discover how far it is from the top.
 * <p>
 * When a stack is first created, it contains no items.
 *
 * <p>A more complete and consistent set of LIFO stack operations is
 * provided by the {@link Deque} interface and its implementations, which
 * should be used in preference to this class.  For example:
 * <pre>   {@code
 *   Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
 *
 * @author  Jonathan Payne
 * @since   JDK1.0
 */
public
class Stack<E> extends Vector<E> {
    /**
     * Creates an empty Stack.
     */
    public Stack() {
    }

    /**
     * Pushes an item onto the top of this stack. This has exactly
     * the same effect as:
     * <blockquote><pre>
     * addElement(item)</pre></blockquote>
     *
     * @param   item   the item to be pushed onto this stack.
     * @return  the <code>item</code> argument.
     * @see     java.util.Vector#addElement
     */
    public E push(E item) {
        addElement(item);

        return item;
    }

    /**
     * Removes the object at the top of this stack and returns that
     * object as the value of this function.
     *
     * @return  The object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E pop() {
        E       obj;
        int     len = size();

        obj = peek();
        removeElementAt(len - 1);

        return obj;
    }

    /**
     * Looks at the object at the top of this stack without removing it
     * from the stack.
     *
     * @return  the object at the top of this stack (the last item
     *          of the <tt>Vector</tt> object).
     * @throws  EmptyStackException  if this stack is empty.
     */
    public synchronized E peek() {
        int     len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }

    /**
     * Tests if this stack is empty.
     *
     * @return  <code>true</code> if and only if this stack contains
     *          no items; <code>false</code> otherwise.
     */
    public boolean empty() {
        return size() == 0;
    }

    /**
     * Returns the 1-based position where an object is on this stack.
     * If the object <tt>o</tt> occurs as an item in this stack, this
     * method returns the distance from the top of the stack of the
     * occurrence nearest the top of the stack; the topmost item on the
     * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt>
     * method is used to compare <tt>o</tt> to the
     * items in this stack.
     *
     * @param   o   the desired object.
     * @return  the 1-based position from the top of the stack where
     *          the object is located; the return value <code>-1</code>
     *          indicates that the object is not on the stack.
     */
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);

        if (i >= 0) {
            return size() - i;
        }
        return -1;
    }

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = 1224463164541339165L;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【数据结构】JavaScript栈实现 的相关文章

  • 是否可以在没有 Javascript(仅 CSS)的情况下执行相同的操作(悬停效果)?

    我正在尝试创建一个带有图标的按钮像这样 http jsfiddle net pRdMc HTML div div class icon div span Send Email span div CSS button width 270px
  • 使用 获取用于 javascript 的 RSA 密钥?

    我的 Web 项目需要一个 RSA 密钥对 虽然有一些库 但我认为依靠浏览器 为了安全性和速度 为我生成密钥是个好主意 是否可以使用注册机或其他浏览器 API 来执行此操作 我不知道如何从注册机获取密钥 它们似乎是在提交时生成的 但我不想将
  • 如何通过aws-sdk(javascript或node)获取s3存储桶大小

    我尝试使用 javascript nodejs aws sdk 查找 获取 s3 存储桶信息 但没有找到这样的 api 如何通过 aws sdk javascript 或 node api 获取 s3 存储桶大小 信息 每天一次向 Clou
  • jQuery UI sortable 和 contenteditable=true 不能一起工作

    我正在创建一个列表并希望使其项目可排序和可编辑 所以我这样做 ul li span A span li li span B span li li span C span li ul ul list sortable http jsfiddl
  • 如果浏览器在 asp .net 中关闭,请从浏览器中注销?

    我的要求有点复杂 用户正在使用 Web 浏览器访问数据库 而在访问数据库时 如果用户关闭活动页面而不是注销会话 该会话需要自动注销 有人可以指导我如何做这个吗 我在母版页中使用了jquery onbeforeunload 我收到消息离开页面
  • 缓存 firestore 中 get 的第一个实现

    我希望 firestore 每次都先从缓存中获取数据 根据 Firestore 文档 传递 缓存 或 服务器 选项必须启用相同的功能 下面的例子 db collection cities where capital true get cac
  • 在 JavaScript 中定位提示弹出窗口

    我有一个如下所示的 JavaScript 提示 我想将提示放在屏幕中心 如何使用 javascript 做到这一点 function showUpdate var x var name prompt Please enter your na
  • 在 IE10 中禁用捏合放大

    在 IE10 触摸模式下 我希望仅使页面的特定部分可缩放 其余的不应该 我找到了这个 http msdn microsoft com en US library ie hh772044 aspx http msdn microsoft co
  • jQuery 检查复选框并触发 javascript onclick 事件

    我正在尝试使用 jQuery 检查复选框并在此过程中触发 onclick 事件 假设我在 html 中定义了一个复选框
  • 离子旋转器未显示

    我用 http 请求填充 Ionic 集合重复列表 但我不想将所有内容直接加载到 DOM 中 因此 我只显示其中一些项目 并在您向下滚动时添加其余项目 为此我实现了无限滚动功能 当我到达页面底部时 它应该显示一个旋转器 但它没有 这些物品至
  • EJS在JS onload函数中访问express变量

    我知道你可以像这样获取 ejs 文件中变量的值 h1 h1 如果我要在同一个 ejs 页面的 onload javascript 函数中使用相同的标题变量 我将如何使用它 例如 这个函数产生一个控制台错误说 未捕获的语法错误 意外的标识符
  • 更改时触发跨度文本/html

    jQuery 或 JavaScript 中是否有任何事件在以下情况下触发span标签 text html 已更改 Code span class user location span user location change functio
  • 获得一次性绑定以适用于 ng-if

    这个问题已经被之前问过 https stackoverflow com questions 23969926 angular lazy one time binding for expressions 但我无法让该解决方案发挥作用 所以我想
  • 从相机视图中拖动锁定在一定距离/半径处的对象

    我在场景中心有一个相机 距离相机 z 400 处有 1 个球体 其父级位于中心 我想从视图中向上 向下 向左 向右拖动球体 但同时不改变它相对于中心的 z 位置 我最终使用了另一个球体并使其不可见 添加side THREE DoubleSi
  • 由于固定导航,增加了 FancyBox v2 的顶部和底部边距

    我目前正在开发一个网站 该网站将来将具有响应能力 该网站主要由图像组成 单击这些图像会加载到 FancyBox 中 FancyBox v2 现在具有响应能力 因此可以在屏幕尺寸发生变化时重新调整图像等的大小 作为我设计的一部分 我有两个固定
  • 如何生成 JavaScript 堆栈跟踪? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 关于如何以跨浏览器的方式在 javascript 中生成堆栈跟踪有什么建议吗 较新的浏览器 Chrome 和 Firefox 公开了一个允
  • 如何在 JavaScript 中对关联数组进行排序?

    我需要为我的一个项目通过 JS 对关联数组进行排序 我发现这个函数在 Firefox 中运行得很好 但不幸的是它在 IE8 OPERA CHROME 中不起作用 无法找到使其在其他浏览器中运行的方法 或者找到另一个适合该目的的函数 我真的很
  • 跨浏览器:禁用输入字段的不同行为(文本可以/不能复制)

    我有一个被禁用的输入 html 字段 在某些浏览器 Chrome Edge Internet Explorer 和 Opera 中可以选择并复制文本 但至少在 Firefox 中这是不可能的 您可以通过在不同浏览器中执行以下代码来测试
  • 如何修复nodejs Express服务器中的“MulterError:意外字段”?

    我正在设置一个服务器来从客户端上传 zip 文件 服务器运行express和multer来执行此操作 上传文件时 服务器抛出 MulterError 意外字段 错误 我无法弄清楚是什么导致了它 我尝试过使用 png 图像 效果很好 但对于
  • openssl_pkey_get_details($res) 不返回公共指数

    我在用着这个例子 https stackoverflow com a 12575951 2016196使用 php 生成的密钥进行 javascript 加密openssl图书馆 但是 details openssl pkey get de

随机推荐

  • MySQL优化-explain执行计划详解

    文章目录 MySQL Query Optimizer简介 MySQL常见瓶颈 覆盖索引 Covering Index 又称为索引覆盖 执行计划 Explain 详解 简介 Explain能得到哪些信息 使用方法 执行计划信息详解 id se
  • php header 404写法 php header函数用法

    php header 404写法 header HTTP 1 1 404 Not Found exit 如果以上代码不凑效 可以试试以下代码 header Status 404 Not Found 最好两段代码都写上 为什么一段代码可以 一
  • 线性代数 --- 投影Projection 六(向量在子空间上的投影)

    向量b在多维子空间上的投影 回顾 任意向量b在另一个向量上 直线上 的投影 在研究向量在子空间上的投影前 先回顾一下前面学习的一个任意向量b在另一个向量a上的投影 共三个部分 1 求权重系数 A constant 基于投影即分量的理论 一个
  • 程序员表白专用: 5 种实用表白方法!帮你快速攻陷心仪女生

    年轻的男女朋友们 今天是一个相当重要的日子 520 不知道是从啥时候开始兴起来的 虽然很多单身的人一看到这个几日就觉得闹心 但也有很大一部分单身人士等待着明天的好机会 毕竟天时地利 这么好的日子一定好好珍惜的 表白的套路很多 但都少不了送花
  • Linux服务器上创建新用户

    Linux服务器上创建账户用到useradd命名 一般常用以下命令 sudo useradd m s bin bash userName 在 home目录下新建userName目录 sudo passwd userName 设置密码 会提示
  • LeetCode 21. 合并两个有序链表(Java)

    题目 将两个有序链表合并为一个新的有序链表并返回 新链表是通过拼接给定的两个链表的所有节点组成的 输入 1 gt 2 gt 4 1 gt 3 gt 4 输出 1 gt 1 gt 2 gt 3 gt 4 gt 4 解答 题目是将两个链表合并
  • antd Form表单给标题头添加图标或一些其他样式

    给表单标题旁添加一个Icon图标并设置一个提示信息 如果就一个icon图标和提示信息可以直接使用Form Item中的tooltip属性 tooltip title Tooltip with customize icon icon
  • 奇迹去掉400级限制的详细修改

    奇迹去掉400级限制的详细修改 我是艾西 今天分享的是奇迹mu如何去掉400级等级限制修改 对于懂技术的小伙伴可以作为参考 更多关于奇迹技术问题可以爱特我 下面我们直接进行操作 直接在scf common ini文件里设置 Common S
  • Python批量管理主机

    18 1 paramiko paramiko模块是基于Python实现的SSH远程安全连接 用于SSH远程执行命令 文件传输等功能 默认Python没有 需要手动安装 pip install paramiko 如安装失败 可以尝试yum安装
  • ReactNative 学习笔记Component 和createClass区别

    Component 更改默认state 中的成员变量 需要调用构造器 getInitialState函数是不会被调用的 pre class javascript class SearchPage extends Component cons
  • js正则匹配不能为空

  • termux怎么生成木马_Termux入侵安卓指南

    apt update 更新源 apt upgrade 升级软件包 pkg install vim curl wget git python nmap 安装基本工具 PS 如果有弹出选项 输入y然后回车即可 安装MSF 进入termux 逐步
  • 【华为OD机试真题2023B卷 JAVA&JS】统计射击比赛成绩

    华为OD2023 B卷 机试题库全覆盖 刷题指南点这里 统计射击比赛成绩 时间限制 1秒 内存限制 65536K 语言限制 不限 题目描述 给定一个射击比赛成绩单 包含多个选手若干次射击的成绩分数 请对每个选手按其最高3个分数之和进行降序排
  • 运算放大器使用的六个经验

    文章目录 1 注意输入电压是否超限 2 不要在运放输出直接并接电容 3 不要在放大电路反馈回路并接电容 4 注意运放的输出摆幅 5 注意反馈回路的Layout 6 要重视电源滤波 2016 2017 小威 家 豫ICP备17018141号
  • Java web期末

    一 简答题 1 Servlet的体系结构 1 Servlet接口 规定了必须由Servlet类实现并且由Servlet引擎识别和管理的方法集 2 GenericServlet抽象类 提供了除service 方法之外其他有关Servlet生命
  • cpu的MMU

    MMU 内存管理单元 用于完成虚拟内存和物理内存的映射 位于CPU内部 我们知道 程序文件一般放在硬盘上 当把程序运行起来时 程序被放入内存中 通过内存放入cache 通过cache进入cpu 下图中预取器就是负责从cache取出指令 然后
  • H5 移动端 时间选择器

    本选择器 自己填充内容 li的文本 只是做了一个大概的样式 其它的有需要者自己去改
  • Ubuntu22.04密码忘记怎么办 Ubuntu重置root密码方法

    在Ubuntu 22 04 或其他更高版本上不小心忘记root或其他账户的密码怎么办 首先uname r查看当前系统正在使用的内核版本 记下来 前提 是你的本地电脑 有物理访问权限 其他如远程登录的不适用这套改密方法 通过以下步骤 无需输入
  • response.text和 response.content的区别:

    1 response content这个是直接从网络上面抓取的数据 没有经过任何解码 所以是一个 bytes类型 其实在硬盘上和在网络上传输的字符串都是 bytes类型 2 response text 这个是 requests 将 resp
  • 【数据结构】JavaScript栈实现

    栈是一种常见的数据结构 常用于app页面堆栈 括号匹配校验 中缀表达式转换 图的深度优先遍历等场景 本文参考java jdk源码 在JavaScript中实现这种数据结构 一 栈的定义 栈是限定仅在表尾进行插入和删除操作的线性表 允许插入和