zoukankan      html  css  js  c++  java
  • 《剑指offer》— JavaScript(20)包含min函数的栈

    包含min函数的栈

    题目描述

      定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。


    实现代码

    var stack = [];
    
    function push(node) {
        stack.push(node);
    }
    
    function pop() {
        return stack.pop();
    }
    
    function top() {
        return stack[0];
    }
    
    function min() {
        return Math.min.apply(this, stack);
    }
    module.exports = {
        push: push,
        pop: pop,
        top: top,
        min: min
    };
    

    相关知识

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

    JavaScript用数组实现栈:

    1. 栈初始化:创建一个空栈
    Init: function () {
        this.STACKMAX = 99;
        this.stack = new Array(this.STACKMACK);
        this.top = -1;
        return this.stack;
    }
    
    1. 判断栈空: 若栈为空返回true,否则返回false
    isEmpty: function () {
        if (this.top == -1) {
            return true;
        } else {
            return false;
        }
    }
    
    1. 进栈:若栈满,返回“栈满”。否则将元素elem作为新的栈顶元素。
    Push: function (node) {
        if (this.top == this.STACKMAX - 1) {
            return new Error("栈满");
        } else {
            this.top++;
            this.stack[this.top] = node;
        }
    }
    
    1. 退栈:删除栈顶元素,并返回其值
    Pop: function () {
        if (this.top == -1) {
            return new Error("空栈,无法删除栈顶元素!");
        } else {
            return this.stack[this.top--];
        }
    }
    
    1. 读栈顶元素:返回栈顶元素
    Top: function () {
        if (this.top != -1) {
            return this.stack[this.top];
        } else {
            return new Error("空栈,顶元素无返回值!");
        }
    }
    
    1. 清空栈:将栈清空为空栈
    Clear: function () {
        this.top = -1;
    }
    
    1. 栈长度:返回栈的元素个数,既栈的长度
    Length: function () {
        return this.top + 1;
    }
    
  • 相关阅读:
    js通过class获取元素时的兼容性解决方案
    html5的八大特性
    typeof与instanceof的区别
    evel()与JSON.parset()的区别
    apt-get出现的问题
    Linux下开启计划任务日志
    ls
    win10自带IE上不了网的解决办法
    crontab -e文件存放路径
    Linux系统下面crontab选择默认编译器
  • 原文地址:https://www.cnblogs.com/echovic/p/6472466.html
Copyright © 2011-2022 走看看