zoukankan      html  css  js  c++  java
  • JavaScript数据结构与算法-栈练习

    栈的实现

    // 栈类
    function Stack () {
        this.dataStore = [];
        this.top = 0; // 栈顶位置 相当于length,不是索引。
        this.push = push;
        this.pop = pop;
        this.peek = peek;
        this.clear = clear;
        this.length = length;
    }
    // push: 入栈
    function push (element) {
        this.dataStore[this.top++] = element;
    }
    // pop: 出栈
    function pop () {
        return this.dataStore[--this.top];
    }
    // peek: 取栈顶元素
    function peek () {
        return this.dataStore[this.top - 1];
    }
    // clear: 清空栈
    function clear () {
        this.top = 0;
    }
    // length: 栈内元素个数
    function length () {
        return this.top;
    }
    

    练习

    一. 栈可以用来判断一个算术表达式中的括号是否匹配。编写一个函数,该函数接受一个算术表达式作为参数,返回括号缺失的位置。下面是一个括号不匹配的算术表达式的例子:2.3 + 23 / 12 + (3.14159 * 0.24。

    function findWrongBrace (express) {
        let s = new Stack();
        for (let i = 0; i < express.length; ++i) {
            if (express[i] === `(`) {
                s.push(i);
            } else if (express[i] === `)`) {
                s.pop();
            }
        }
        return `${express}的第${s.peek() + 1}个字符是不匹配的括号。`;
    }
    // 示例
    console.log(findWrongBrace(`2.3 + 23 / 12 + (3.14159 * 0.24`)); // 2.3 + 23 / 12 + (3.14159 * 0.24的第17个字符是不匹配的括号。
    

    二. 现实生活中栈的一个例子是佩兹糖果盒。想象一下你有一盒佩兹糖果,里面塞满了红色,黄色和白色的糖果,但是你不喜欢黄色的糖果。使用栈(有可能用到多个栈)写一段程序,在不改变盒内其他糖果叠放顺序的基础上,将黄色糖果移除。

    let Candy = `rywrryywwrrryyywww`, newCandy = ``; // 模拟糖果
    let s = new Stack();
    let len = Candy.length;
    while (len--) {
        if (Candy[len] !== `y`) {
            s.push(Candy[len]);
        }
    }
    while (s.length()) {
        newCandy += s.pop();
    }
    console.log(newCandy); // rwrrwwrrrwww
    

    JavaScript数据结构与算法-栈练习

  • 相关阅读:
    commons-logging.jar 和 log4j.jar 的关系
    百钱买百鸡
    reflect
    golang结构体、接口、反射
    golang文件操作
    sqlx使用说明
    go example
    goroutine
    生成二维码
    method&interface
  • 原文地址:https://www.cnblogs.com/mazey/p/8322354.html
Copyright © 2011-2022 走看看