链表

2019-08-09  本文已影响0人  lacduang

链表的方法

结点

var Node = function(data) {
  this.data = data
  this.next = null
}

链表的实现

function LinkList() {
  // 定义节点
  var Node = function(data) {
    this.data = data
    this.next = null
  }

  var length = 0        // 长度
  var head = null       // 头节点
  var tail = null       // 尾结点

  // 添加结点
  this.append = function(data) {
    // 创建节点
    var new_node = new Node(data)
    if(head == null) {
      head = new_node
      tail = new_node
    } else {
      tail.next = new_node
      tail = new_node
    }
    length += 1;
    return true
  }
  
  // 打印节点
  this.print = function() {
    var curr_node = head
    while(curr_node) {
      console.log(curr_node.data)
      curr_node = curr_node.next
    }
  }
  this.insert = function(index, data) {
    if(index < 0 && index > length) {
      return false
    } else if(index === length) {
      return this.append(data)
    } else {
      var new_node = new Node(data)
      // new_node变成新的头节点
      if(index == 0) {
        new_node.next = head
        head = new_node
      } else {
        var insert_index = 1
        var curr_node = head
        while(insert_index < index){
          insert_index += 1
          curr_node = curr_node.next
        }
        // 当循环结束的时候
        var next_node = curr_node.next
        curr_node.next = new_node
        new_node.next = next_node
      }
      length += 1
      return true
    }
  }

  // 移除节点
  this.remove = function(index) {
    if(index < 0 || index >= length) {
      return null
    } else {
      var del_node = null
      if(index == 0) {
        del_node = head
        head = head.next
      } else {
        var del_index = 0
        var pre_node = null     // 被删除节点的前一个节点
        var curr_node = head    // 要被删除的节点
        while(del_index < index) {
          del_index += 1
          pre_node = curr_node
          curr_node = curr_node.next
        } 

        del_node = curr_node
        // 被删除节点的前一个节点指向被删除节点的后一个节点
        pre_node.next = curr_node.next

        // 如果被删除的节点是尾结点
        if(curr_node.next == null) {
          tail = pre_node
        }
      }

      length -= 1
      del_node.next = null
      return del_node.data
    } 
  }

  //  返回指定位置节点的值
  this.get = function(index) {
    if(index < 0 || index >= length) {
      return null
    }

    var node_index = 0
    var curr_node = head
    while(node_index < index) {
      node_index += 1
      curr_node = curr_node.next
    }
    return curr_node.data
  }
}
上一篇下一篇

猜你喜欢

热点阅读