【数据结构】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栈实现 的相关文章

随机推荐

  • 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中实现这种数据结构 一 栈的定义 栈是限定仅在表尾进行插入和删除操作的线性表 允许插入和