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

  • 相关阅读:
    路由器01---k2刷Pandora
    nginx+flask02---概念
    Nginx06---实现websocket
    Nginx05---负载均衡 upsteam
    nginx+uwsgi02---django部署(推荐)
    Nginx04---实现直播
    Nginx04---编译安装
    mybatis+mysql insert添加数据后返回数据主键id---(转)
    JSON字符串转换为Map
    Http post请求案例
  • 原文地址:https://www.cnblogs.com/frankltf/p/7561713.html
Copyright © 2011-2022 走看看