当前位置: 移动技术网 > IT编程>开发语言>JavaScript > javascript编程实现栈的方法详解【经典数据结构】

javascript编程实现栈的方法详解【经典数据结构】

2018年06月06日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网