本文实例讲述了javascript编程实现栈的方法。分享给大家供大家参考,具体如下:
栈是限定仅在表尾进行插入或删除操作的线性表,栈是先进后出的。栈的表尾称为栈顶(top),而表头端称为栈底(bottom)。
和线性表类似,栈也有两种存储表示方法,顺序栈和链栈。
这里讲一下顺序栈,设置指针top指示栈顶元素在顺序栈中的位置。通常的做法就是以top=0表示空栈。base为栈底指针,top为栈顶指针。
如果base为null,则表示栈结构不存在,如果top=base则表示空栈。每当插入一个新的元素,top+1,删除元素,top-1。因此,非空栈中top始终在栈顶元素的下一位置上。
如下图所示
JavaScript中自带了数组的push和pop方法,其原理无非就是数组最后继续添加和删除数组最后一个元素。这里我们自己实现一遍栈的操作,代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS栈</title> </head> <body> <script type="text/javascript"> function Stack(count){ var top=-1;//top头指针 this.myArray=new Array(); if(count!=undefined){ this.count=count; this.myArray=new Array(this.count); }else{ this.count=0; } //入栈 this.In=function(value){ if(top==this.count){ return false; }else{ ++top; this.myArray[top]=value; return true; } return false; } //出栈 this.Out=function(){ if(top==-1){ return false; }else{ var removeValue=this.myArray[top]; this.myArray[top]=null; top--; return removeValue; } } this.Clear=function(){ this.top=-1; } //遍历栈 this.tostring=function(){ for(var i=0;i<this.myArray.length;i++){ document.write(this.myArray[i]+'<br>'); } } } Stack(3); In(1); In(2); In(3); tostring();//1 2 3 Out(); Out(); tostring();//1 null null In(4); tostring();//1 4 null </script> </body> </html>
首先需要定义头指针
function Stack(count){ var top=-1;//top头指针 this.myArray=new Array(); if(count!=undefined){ this.count=count; this.myArray=new Array(this.count); }else{ this.count=0; }
然后是入栈操作
//入栈 this.In=function(value){ if(top==this.count){ return false; }else{ ++top; this.myArray[top]=value; return true; } return false; }
和出栈操作
//出栈 this.Out=function(){ if(top==-1){ return false; }else{ var removeValue=this.myArray[top]; this.myArray[top]=null; top--; return removeValue; } }
链栈的操作和链表类似,这里就不做详细介绍了。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 《腾格尔 容中尔甲 亚东 高原三星 男人篇 3CD》[WAV/分轨][1GB]
- 命运圣契公测实测可用兑换码大全 命运圣契最新兑换码分享
- 黑神话悟空上品疾蝠精魄获取方法一览|上品疾蝠精魄收集攻略
- 《七龙珠电光炸裂!ZERO》GT角色预告片曝光,15位新角色登场
- [ABC]安娜-胆麦发烧女声[6N纯银镀膜][2016[低速原抓WAV+CUE]
- NewViennaOctetViennaWindSoloists-TheDeccaRecordings(2024)18CD[24-48][FLAC]-7
- 雨果唱片-三角琴《俄罗斯民间音乐系列-梁祝(中国名曲)》wav
- 《塞尔达传说:智慧的再现》新实机!无之世界介绍
- 任天堂公布《塞尔达传说》系列时间线:野炊与王泪独立在外
- 任天堂更新网络投稿规范:打击影响他人游戏体验行为
- 冼佩瑾.2024-女儿Daughter(EP)【杰威尔】【FLAC分轨】
- 黑豹乐队.1993-光芒之神【摇音晨【WAV+CUE】
- 曾轶可.2011-一只猫的旅行【天娱传媒】【WAV+CUE】
- 黑神话悟空上品狼刺客精魄获取方法一览|上品狼刺客精魄收集攻略
- 视觉小说《神椿市建设中REGENERATE》将于2025年2月20日发售