侧边栏壁纸
博主头像
落叶人生博主等级

走进秋风,寻找秋天的落叶

  • 累计撰写 129149 篇文章
  • 累计创建 28 个标签
  • 累计收到 9 条评论
标签搜索

目 录CONTENT

文章目录

js数据结构——栈

2024-04-28 星期日 / 0 评论 / 0 点赞 / 2 阅读 / 1812 字

function Stack(){ var items = []; //动态原型模式 if(typeof this.pop != "function"){

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()函数实现入栈和出栈。

广告 广告

评论区