• 栈的实现 -- 数据结构与算法的javascript描述 第四章


    栈 :last-in-first-out

    栈有自己特殊的规则,只能 后进入的元素 ,最先被推出来,我们只需要模拟这个规则,实现这个规则就好。 peek是返回栈顶元素(最后一个进入的)。

      /**
         * 栈 后入先出
         * @constructor
         */
        function Stack(){
            this.pop = pop;
            this.push = push
            //栈顶位置
            this.top= 0;
            this.length = 0;
            this.dataStore = [];
            this.peek = peek;
            this.clear = clear;
            this.length = length;
    
            //返回栈顶元素
            function peek(){
                return this.dataStore[this.top-1];
            }
    
            function clear(){
                this.top=0;
                this.dataStore=[];
            }
            function length (){
                return this.top;
            }
            function pop(){
                return this.dataStore[--this.top];
            }
            function push(element){
                this.dataStore[this.top++]=element;
            }
    
            function empty(){}
    
        }
        //栈的应用
        /**
         * 进制转换
         * @param num  数字 *10进制
         * @param base  转换进制 任何进制
         * @returns {string}
         */
        function mulBase(num, base) {
            var s = new Stack();
            do {
                s.push(num % base);
                num = Math.floor(num /= base);
            } while (num > 0);
            var converted = "";
            while (s.length() > 0) {
                converted += s.pop();
            }
            return converted;
        }
        var s = mulBase(32,2)
        console.log(s)
    
        /**
         * 判断字符是否  回文    *回文是指这样一种现象:一个单词、短语或数字,从前往后写和从后往前写都是一样的。
         * @param word
         * @returns {boolean}
         */
        function ishuiwen(word){
            var s = new Stack()
            for(var i=0;i<word.length;i++){
                s.push(word[i])
            }
            var foword = '';
    
            while(s.length()>0){
                foword+=s.pop()
            }
            return word==foword;
        }
        var hs = 'aca'
        console.log(hs+"判断是否回文:"+ishuiwen(hs))
    
  • 相关阅读:
    深拷贝和浅拷贝
    【.NET MVC分页】.NET MVC 使用pagelist 分页
    Win10开启IIS
    Win10开启IIS
    目前问题:plupload上传带参数到后台
    目前问题:plupload上传带参数到后台
    jquery怎样获取html页面中的data-xxx
    .Net MVC删除图片
    .Net MVC删除图片
    AlloyClip的简单使用
  • 原文地址:https://www.cnblogs.com/iyueyao/p/3968820.html
Copyright © 2020-2023  润新知