Javascript与数据结构系列(三)——链表的完成

链表完成

设想一个基于对象的链表 我们设想的链表包含两个类。

  • Node 类用来示意节点

  • LinkedList 类供应了插进去节点、删除节点、显现列表元素的要领,以及其他一些辅佐要领。

Node类

Node 类包含两个属性:element 用来保留节点上的数据,next 用来保留指向下一个节点的
链接。我们运用一个组织函数来建立节点,该组织函数设置了这两个属性的值:

 function Node(element) {
    this.element = element;
    this.next = null;
 } 

LinkedList类

LList 类供应了对链表举行操纵的要领。该类的功用包含插进去删除节点、在列表中查找给 定的值。该类也有一个组织函数,链表只要一个属性,那就是运用一个 Node 对象来保留该 链表的头节点。
该类的组织函数以下所示:

function LList() {
    this.head = new Node("head");
    this.find = find;
    this.insert = insert;                                  
    this.remove = remove;
    this.display = display;
}

代码归结

function Node(element) {
  this.element = element;
  this.next = null;
}

function LList() {
  this.head = new Node("head");
  this.find = find;
  this.insert = insert;
  this.display = display;
  this.findPrevious = findPrevious;
  this.remove = remove;
}

function remove(item) {
  var prevNode = this.findPrevious(item);
  if (!(prevNode.next == null)) {
    prevNode.next = prevNode.next.next;
  }
}

function findPrevious(item) {
  var currNode = this.head;
  while (!(currNode.next == null) &&
    (currNode.next.element != item)) {
    currNode = currNode.next;
  }
  return currNode;
}

function display() {
  var currNode = this.head;
  while (!(currNode.next == null)) {
    print(currNode.next.element);
    currNode = currNode.next;
  }
}

function find(item) {
  var currNode = this.head;
  while (currNode.element != item) {
    currNode = currNode.next;
  }
  return currNode;
}

function insert(newElement, item) {
  var newNode = new Node(newElement);
  var current = this.find(item);
  newNode.next = current.next;
  current.next = newNode;
}

后话

固然,学好前端,你还需要关注一个民众号!——逐日前端
列位兄弟姐妹,共勉!
《Javascript与数据结构系列(三)——链表的完成》

    原文作者:Vagor
    原文地址: https://segmentfault.com/a/1190000004921407
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞