• 《剑指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;
    }
    
  • 相关阅读:
    Mac OS X从10.7升级到Mountain Lion OS X10.8
    IOS UIView,UIViewController
    ObjectiveC Content list
    Sharepoint 系统管理
    iOS UIViewController use
    WIN10关机常用的三种方法
    svn check build
    ubuntu下搭建android开发环境
    BitmapFactory.Options避免 内存溢出 OutOfMemoryError的优化方法
    ubuntu update source with proxy
  • 原文地址:https://www.cnblogs.com/echovic/p/6472466.html
Copyright © 2020-2023  润新知