zoukankan      html  css  js  c++  java
  • 栈的实现 -- 数据结构与算法的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))
    
  • 相关阅读:
    Qt之镜像旋转
    Qt之QCheckBox
    Qt之动画框架
    Qt之QFileSystemWatcher
    Qt之qSetMessagePattern
    Qt之qInstallMessageHandler(重定向至文件)
    Qt之qInstallMessageHandler(输出详细日志)
    Qt之窗体透明
    Qt之窗体拖拽、自适应分辨率、自适应大小
    Qt之设置应用程序图标
  • 原文地址:https://www.cnblogs.com/iyueyao/p/3968820.html
Copyright © 2011-2022 走看看