本文实例讲述了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程序设计有所帮助。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。