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

  • 相关阅读:
    SVN访问配置及常用操作
    SVN配置
    在Eclipse中创建maven项目
    Maven的基础之环境配置
    线程池理解
    JVM之类的生命周期
    JAVA代码编程规范
    Jquery实现div局部页面刷新中js渲染失效问题解决
    觅踪17
    第十四周进度
  • 原文地址:https://www.cnblogs.com/frankltf/p/7561713.html
Copyright © 2011-2022 走看看