使用Javascript链接列表数据结构

时间:2016-07-13 18:31:04

标签: javascript data-structures linked-list

我正在尝试使用Javascript找出链表数据结构。但有一部分我无法理解。

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

  var length = 0;
  var head = null;

  this.append = function(element) {
    var node = new Node(element),
      current;

    if (head === null) {
      head = node;
    } else {
      current = head;

      //loop the list until find last item
      while (current.next) {
        current = current.next
      }

      //get last item and assign next to node to make the link
      current.next = node
    }
    length++;
  }

  this.removeAt = function(position) {
    //check for out of bounds values
    if (position > -1 && position < length) {
      var current = head,
        previous,
        index = 0;

      if (position === 0) {
        head = current.next;
      } else {
        while (index++ < position) {
          debugger;
          previous = current;
          current = current.next;
        }

        previous.next = current.next;
      }

      length--;

      return current.element;

    } else {
      return null;
    }
  }

  this.toString = function() {
    var current = head,
      string = '';

    while (current) {
      string = current.element;
      current = current.next;
    }

    return string;
  }
}

var list = new LinkedList();
list.append(15);
list.append(10);
list.append(11);
list.removeAt(1);

我不明白变量 当前 在运行 removeAt 方法时如何丢失对该节点的引用。

1 个答案:

答案 0 :(得分:1)

如果要创建链接列表,可以使用以下算法:-

var linkedList = function(){
  this.head=null;
  this.tail=null;
  this.size=0;
}
linkedList.prototype.add=function(obj){
 if(!this.head){
   this.head=obj;
   this.tail=obj;
   this.size++;
   return
 }
 this.tail.next = obj;
 this.tail=obj;
 this.size++;
}