宝哥软件园

JS栈类的实现和使用示例

编辑:宝哥软件园 来源:互联网 时间:2021-08-27

本文通过实例描述了JS栈类的实现和使用。分享给大家参考,如下:

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

示例代码:

/*使用堆栈的实现堆栈类*/functionstack () {this。datastore=[];//保存堆栈中的元素,并将其初始化为空数组this . top=0;//在栈顶,初始化为0 this.push=push//stack this . pop=pop;//stack this . peek=peek;//检查堆栈顶部元素this.clear=clear//空堆栈this.length=length//堆栈中存储的元素数}函数push(element){ this . datastore[this . top]=element;}函数pop(){ return this . Datastore[-this . top];}函数peek(){返回this . Datastore[this . top-1];}函数clear(){ this . top=0;}函数length(){ return this . top;}/*测试堆栈类的实现*/var s=new stack();s . push(' aa ');s . push(' bb ');s . push(' cc ');console . log(s . length());//3 con sole . log(s . peek());//ccvar popled=s . pop();console.log(已弹出);//ccconsole . log(s . peek());//bb在这里,使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,得到如下运行结果:

更多对JavaScript相关内容感兴趣的读者可以查看本网站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、0103010

希望本文对JavaScript编程有所帮助。

更多资讯
游戏推荐
更多+