JavaScript实现单链表

来源:互联网 发布:安藤忠雄小筱邸数据 编辑:程序博客网 时间:2024/06/05 01:15
<!DOCTYPE html>  <html>  <head>  <script type = "text/javascript">      var array = new Array(1,2,3,4,5,6);      var Node = function(newData){          this.next = null;          this.data = null;          this.Init = function(){              this.data = newData;          };          this.Init();      }      //definition of List class       var List = function(){          this.head = null;          this.size = 0;          this.Init = function(){              this.head = null;              this.size = 0;          }          this.Init();                    this.Insert = function(newData){              this.size += 1;              var newNode = new Node(newData);              if(this.head == null){                  this.head = newNode;                  return;              }              var tempNode = this.head;              while(tempNode.next != null)                  tempNode = tempNode.next;              tempNode.next = newNode;          };                    this.GetData = function(pos){              if(pos >= this.size || pos < 0)                  return null;                else{                  tempNode = this.head;                  for(i = 0;i < pos;i++)                        tempNode = tempNode.next;                    return tempNode.data;                 }          };                    //remove the element at pos          this.Remove = function(pos){              if(pos >= this.size || pos < 0)                  return null;                  this.size -= 1;              tempNode = this.head;              if(pos == 0){                  this.head = this.head.next;                  return this.head;              }              for(i = 0;i < pos - 1;i++){                  tempNode = tempNode.next;              }              tempNode.next = tempNode.next.next;              return tempNode.next;                            }                    this.Print = function(){              document.write("elements in list as follows: <br>");              tempNode = this.head;              while(tempNode != null){                  document.write(tempNode.data + " ");                  tempNode = tempNode.next;              }              document.write("<br>");          };      };            //RUN TEST:      var list = new List();      var array = new Array(1,2,3,4,5,6);      for(i = 0;i < array.length;i++){          list.Insert(array[i]);      }      list.Print();      document.write("now remove action:4 <br>");      list.Remove(4);      list.Print();      document.write("new size after Remove list[5]:  " + list.size);    </script>  </head>    <body>  </body>  </html>

0 0
原创粉丝点击