JS封装基于数组的栈类

栈结构

是一种受限的线性结构,

只能在栈顶添加/删除元素。

后进先出 LIFO

例如:自助餐的托盘,实体邮件。

函数调用栈

A调用BB调用CC调用DA被放在了栈底,BA的上边,CB的上边,D在栈顶
D被执行完后会先弹出栈

递归:连续不断调用自己;容易出现栈溢出

654321顺序进栈
不合法的出栈顺序是:C
A.543612	B.45321		C.346521	D.234156

实现基于数组的栈

//封装基于数组的栈
         function Stack(){
            this.items=[];
            // 1入栈 push 
            Stack.prototype.push=function(Element){
                this.items.push(Element);
            }
            //2.出栈 pop
            Stack.prototype.pop=function(){
                this.items.pop();
            }
            // 3.查看栈顶 peek
            Stack.prototype.peek=function(){
                return this.items[this.items.length-1];
            }
            // 判空
            Stack.prototype.isEmpty=function(){
                return this.items.length==0;
            }
            //返回元素个数 size
            Stack.prototype.size=function(){
                return this.items.length;
            }
            //toString
            Stack.prototype.toString=function(){
                var resultString="";
                for(var i=0;i<this.items.length;i++){
                    resultString+=this.items[i]+" ";
                }
                return resultString;
            }
        }
        var s= new Stack();
        // 入栈
        s.push(110);
        s.push(120);
        s.push(130);
        s.push(140);//110 120 130 140 
        // 出栈
        s.pop();//110 120 130 
        // 查看栈顶
        console.log(s.peek());
        // 判空
        console.log(s.isEmpty());
        // 返回元素个数
        console.log(s.size());
        // 输出数组大的toString
        console.log(s.toString());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@小玉同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值