JavaScript 数据结构 --- 栈

4 篇文章 0 订阅
1 篇文章 0 订阅

JavaScript 数据结构 — 栈

一,栈的基本操作

1,push(elemenet):压栈,添加一个新元素到栈顶位置
2,pop():出栈,移除栈顶元素,同时返回被移除的元素
3, peek():返回栈顶元素,不对栈做任何修改(这个方法不会移除栈顶元素,仅仅返回它)
4,isEmpty():(empty:空的)栈为空,返回true,栈不为空,返回false
5,size():返回栈里元素个数,与数组中的length方法类似
6,toString():将栈结构的内容以字符串的形式返回

二,封装栈

 function Stack() {
            //栈中的属性
            this.item = [],
                //栈的相关操作
                //push
                Stack.prototype.push = function (element) {
                    this.item.push(element);
                }
            Stack.prototype.pop = function () {
                return this.item.pop();
            }
            Stack.prototype.peek = function () {
                return this.item[this.item.length - 1];
            }
            Stack.prototype.isEmpty = function () {
                return this.item.length === 0;
            }
            Stack.prototype.size = function () {
                return this.item.length;
            }
            Stack.prototype.toString = function () {
                let resultString = '';
                for (let i = 0; i < this.item.length; i++) {
                    resultString += this.item[i] += " ";
                }
                return resultString;
            }
        }

三,测试

  var s = new Stack();
        s.push(10);
        s.push(20);
        s.push(30);
        s.push(80);
        console.log(s.toString());   //10 20 30 80
        s.pop();
        console.log(s.toString());   //10 20 30
        console.log(s.peek());       //30
        console.log(s.isEmpty());    //false
        console.log(s.size());       //3

四,例:应用栈将十进制转二进制

        function decToBin(decNumber) {
            //1,定义一个栈对象
            var stack = new Stack();
            //2,循环操作
            while (decNumber > 0) {
                //2.1获取余数,并将余数压入栈中
                stack.push(decNumber % 2);
                //2.2获取整除后的结果,作为下一次运行的数字
                decNumber = Math.floor(decNumber / 2);
            }
            //3,从栈中取出0和1
            var binaryString = "";
            while (!stack.isEmpty()) {
                binaryString += stack.pop();
            }
            return binaryString;
        }
        //测试十进制转二进制的函数
        var num = 1000;
        console.log(decToBin(num));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值