js数据结构及算法——封装简单栈

//Method--方法:和某一个对象实例有联系
        //function--函数
        //封装栈类
        function Stack() {
            //栈的属性
            this.items = []
            //栈的向光操作
            //1.将元素压入栈内
            // this.push = function () { }//此方式相当于给某个对象实例添加方法(每个实例都添加,占用了内存)
            Stack.prototype.push = function (element) {//此方法相当于给整个类添加方法(更节省内存/更高效)
                this.items.push(element);
            }
            //2.从栈中取出元素
            Stack.prototype.pop = function () {
                return this.items.pop();
            }
            //3.查看一下栈顶元素
            Stack.prototype.peek = () => {
                return this.items[this.items.length - 1];
            }
            //4.判断栈是否为空
            Stack.prototype.isEmpty = () => {
                return this.items.length == 0;
            }
            //5.获取栈中元素的长度
            Stack.prototype.size = () => {
                return this.items.length;
            }
            //6.toString方法
            Stack.prototype.toString = () => {
                let getString = ""
                for (let i = 0; i < this.items.length; i++) {
                    getString += this.items[i] + " ";
                }
                return getString;
            }
        }
        //栈的使用
        // let a = new Stack();
        // a.push(10);
        // a.push(20);
        // a.push(30);
        function dec2bin(decNumber) {
            //1.定义栈对象
            let stack = new Stack()
            //2.循环操作
            while (decNumber > 0) {
                stack.push(decNumber % 2);
                decNumber = Math.floor(decNumber / 2);
            }
            let getBin = "";
            while (!stack.isEmpty()) {
                getBin += stack.pop()
            }
            return getBin
        }
        console.log(dec2bin(10))

 

posted @ 2020-05-04 21:10  问问大将军  阅读(254)  评论(0编辑  收藏  举报