怎么在JavaScript中实现一个堆栈类

  介绍

怎么在JavaScript中实现一个堆栈类?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

栈是一种“先进后出”的数据结构,原理如下图所示:

怎么在JavaScript中实现一个堆栈类

示例代码:

/*使用栈栈类的实现*/function 堆栈(),{   时间=this.dataStore 才能;[];//保存栈内元素,初始化为一个空数组   时间=this.top 才能;0;//栈顶位置,初始化为0   this.push =,才能推动;//入栈   时间=this.pop 才能;流行;//出栈   this.peek 才能=,peek;//查看栈顶元素   this.clear =,才能清晰;//清空栈   时间=this.length 才能;长度;//栈内存放元素的个数   }   function 推动(元素){   this.dataStore才能(this.top + +),=,元素;   }   function  pop () {   return 才能this.dataStore [——this.top];   }   function  peek () {   return 才能this.dataStore [this.top-1];   }   function  clear () {   时间=this.top 才能;0;   }   function 长度(){   return 才能;this.top;   }/*测试堆栈类的实现*/var  s =, new 堆栈();   s.push (“aa");   s.push (“bb");   s.push (“cc");   console.log (s.length ());//3   console.log (s.peek ());//cc   var  popped =, s.pop ();   console.log(突然);//cc   console.log (s.peek ());//bb

这里使用<强>在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:

怎么在JavaScript中实现一个堆栈类

看完上述内容,你们掌握怎么在JavaScript中实现一个堆栈类的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

怎么在JavaScript中实现一个堆栈类