zoukankan      html  css  js  c++  java
  • 数据结构与算法 --- js描述栈

    js描述栈及栈的使用

    • 栈的特性就是只能通过一端访问,这一段就是叫做栈顶。咖啡馆内的一摞盘子就是最形象的栈的例子;
    • 根据栈的特性,就可以定义栈的一些特殊属性和方法;用js的描述栈的时候底层数据结构用的是数组,通过this.top来跟踪最后一个元素的索引来实现栈的数据结构;
    function Stack(){
        this.dataSource=[];
        this.top=0;
        this.push=push;
        this.pop=pop;
        this.peek=peek;
        this.clear=clear;
        this.length=length;
    }
    function push (element){
        this.dataSource[this.top++]=element;
    }
    function pop(){
        return this.dataSource[--this.top];
    }
    function peek(){
        return this.dataSource[this.top-1];
    }
    function clear(){
        this.dataSource=[];
        this.top=0;
    }
    function length(){
        return this.top;
    }
    

    栈的使用场景

    • 回文:即一个字符串的正序和反序 。例如hello的反序是olleh;
    //回文实例
    function isPalindRome(word){
        var w=new Stack();
        for(var i=0;i<word.length;i++){
            w.push([word[i]]);
        }
        console.log(w.dataSource);//hello
        var rword='';
        while (w.length()>0){
            rword+= w.pop();
        }
        console.log(rword);  //olleh
    }
    var str='hello';
    

    递归

    • 以10的阶乘为例
    //递归实现5的阶乘
    function fact(n){
        var e=new Stack();
        while (n>=1){
            e.push(n--);
        }
        console.log(e.dataSource);
        var product=1;
        while (e.length()>0){
            product=product* e.pop();
        }
        console.log(product);
    
    }
    fact(10)
    

    github:https://github.com/Frankltf/js-Stack/tree/features-one

  • 相关阅读:
    算法
    如果业界中不用高级算法和数据结构,那为什么还要学?
    CentOS 7 运行级别切换
    ECharts笔记
    Vue+TypeScript学习
    TypeScript深入学习
    TypeScript基础
    检测数据类型的方法
    前端提高性能的方式
    柯里化
  • 原文地址:https://www.cnblogs.com/frankltf/p/7561713.html
Copyright © 2011-2022 走看看