在javascript中使用链表

Dar*_*lyn 5 javascript arrays linked-list

在javascript中使用链表有什么好处吗?它对数组的主要优点(例如)是我们可以在不移动每个元素的情况下在随机索引处插入元素,并且它们不受数组大小的限制。

但是,JS 中的数组是动态扩展、收缩的,数组访问数据的速度更快。我们也可以使用Array.prototype.splice()方法(确实链表可能比这个更快)来插入数据。

那么在 JavaScript 中使用链表而不是数组有什么优势(速度等)吗?

使用 JS 的基本链表代码。

function list() {

  this.head = null;
  this.tail = null;

  this.createNode=function(data) {
    return {data: data, next: null }
  };

  this.addNode=function(data) {
    if (this.head == null) {
      this.tail = this.createNode(data);
      this.head = this.tail;
    } else {
      this.tail.next = this.createNode(data);
      this.tail = this.tail.next;
    }
  };

  this.printNode=function() {
    var x = this.head;
    while (x != null) {
      console.log(x.data);
      x = x.next;
    }
  }
}

var list = new list();
list.addNode("one");
list.addNode("two");
list.printNode();
Run Code Online (Sandbox Code Playgroud)

Sig*_*ied 1

我不知道性能差异。正如你所说,链表在内存分配、垃圾收集、稀疏性方面比其他语言中的数组有优势,但 Javascript 数组可以处理其中一些问题。尽管如此,如果您的用例需要这种数据结构,您仍然可能有理由使用链表:也就是说,您只需要从前端(或双向链表的任一端)开始并从 item 开始访问项目到下一项,无需通过数组索引进行随机访问。

这里有一些关于链表的丰富多彩的隐喻:什么是链表的实用的、现实的例子?