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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

布瑞泽的童话   2020-05-15 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们