js数据结构——栈

function Stack(){
       var items = [];
       //动态原型模式
       if(typeof this.pop != "function"){
           //入栈
           Stack.prototype.push = function(element){
               items.push(element);
           }
           //出栈
           Stack.prototype.pop = function(){
               return items.pop();
           }
           //返回栈顶的元素
           Stack.prototype.peek = function(){
               return items[items.length-1];
           }
           //判断是否栈空
           Stack.prototype.isEmpty = function(){
               return items.length == 0;
           }
           //移除栈里所有元素
           Stack.prototype.clear = function(){
               items = [];
           }
           //返回元素的个数
           Stack.prototype.size = function(){
               return items.length;
           }
           //打印栈里的元素
           Stack.prototype.print = function(){
               console.log(items.toString());
           }
       }
   }
    var stack = new Stack();
   //入栈5个元素 并打印
    stack.push(5);
    stack.push(8);
    stack.push(1);
    stack.push(10);
    stack.push(7);
    stack.print();              //5,8,1,10,7
    //输出栈的大小
    console.log(stack.size());  //5
    //取出栈顶元素并打印
    console.log(stack.peek());  //7
    stack.print();              //5,8,1,10,7
    //出栈并打印
    stack.pop();
    stack.print();              //5,8,1,10
    //清空栈并判空
    stack.clear();
    console.log(stack.isEmpty());//true

由上段代码:

(1)使用动态原型模式创建对象

(2)利用数组,和数组的push()和pop()函数实现入栈和出栈。

转载于:https://my.oschina.net/wyc1219/blog/828995

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值