js算法与数据结构-链表

一、链表的定义

每个元素都带有下一个元素的位置。
js算法与数据结构-链表_第1张图片

二、链表的方法

js算法与数据结构-链表_第2张图片

三、js实现如下

var LinkedList = function(){
  //head
  var head = null
  var length = 0;
  //辅助类
  var Node = function(element){
    this.element = element
    this.next = null
  }
  //添加链表元素
  this.append = function(element){
    var node = new Node(element)
    if(head == null){
      head = node
    }else{
      var current = head
      while(current.next){
        current = current.next
      }
      current.next = node 
    }
    length++
  }
  //获取链表头
  this.getHead = function(){
    return head
  }
  //元素的数量
  this.size = function(){
    return length
  }
  //是否为空
  this.isEmpty = function(){
    return this.size == 0
  }

  //插入元素到链表中
  //1.插入表头
  //2.插入链表中间
  this.insert = function(postion, element){
    var node = new Node(element)
    if(postion > -1 && postion < length){
      if(postion == 0){
        var current = head
        head = node
        node.next = current
      }else{
        //先定义两个相邻的元素遍历链表,找到指定的位置
        //后插入指定的位置
        var index = 0
        var previous = null 
        var current = head
        while(index < postion){
          previous = current
          current = current.next
          index++
        }
        previous.next = node
        node.next = current
      }
      length++
    }
  }
    //移除链表中指定的元素
    //1.移除表头
    //2.移除其它元素
    this.removeAt = function(postion){
      if(postion > -1 && postion < length){
        if(postion == 0){
          var current = head
          head = current.next
        }else{
          var index = 0
          var previous = null
          var current = head
          while(index < postion){
            previous = current
            current = current.next
            index++
          }
          previous.next = current.next
        }
        length--
        return current
      }
    }
    //查询元素值对应index索引号
    this.indexOf = function(element){
      var current = head
      var index = 0
      while(current){
        if(current.element == element) return index
        current = current.next
        index++
      }
      return -1
    }
    //根据元素值删除指定的元素
    this.remove = function(element){
      return this.removeAt(this.indexOf(element))
    }

}
//测试用例
//创建一个链表对象
var l = new LinkedList()
//给链表添加元素
l.append(1)
l.append(2)
l.append(3)

js实现的要点

在实现对链表的操作时,往往要进行遍历链表,而进行遍历必定要使用表头,把表头赋值给遍历变量,再利用链表特性,即每个元素都带有下一个元素的位置 如上述代码 current = current.next 这样就可以依次遍历每个元素。

四、测试

给链表添加元素

js算法与数据结构-链表_第3张图片

你可能感兴趣的:(javascript,算法-数据结构)