【问题标题】:How to improve performance for get in Linked list?如何提高获取链接列表的性能?
【发布时间】:2020-06-02 18:04:48
【问题描述】:

我尝试自己实现一个链表,但遇到了一个问题:“我如何才能获得 O(1) 复杂度的 Node?”

是否有机会(或良好做法)来改进“获取”方法?我需要在链表中添加另一个数据结构吗?我读过一些关于在链表中使用哈希表的文章。正常吗?

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  // O(1)
  addToTail(value) {
    let newNode = new Node(value);

    if (this.head === null) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
  }

  // O(n)
  get(value) {
    let cur = this.head;
    while (cur && cur.value !== value) {
      cur = cur.next;
    }

    return cur;
  }

  // O(n)
  remove(value) {
    let cur = this.head;
    let prev = null;
    while (cur && cur.value !== value) {
      prev = cur;
      cur = cur.next;
    }

    if (cur) {
      // First Node
      if (this.head === cur) {
        this.head = cur.next;
        if (this.head === null) {
          this.tail = null;
        }
      } else {
        // Not first Node
        prev.next = cur.next;

        if (cur.next === null) {
          this.tail = prev;
        }
      }

      return true;
    }

    return false;
  }

  print() {
    let cur = this.head;
    while (cur !== null) {
      console.log(cur.value);
      cur = cur.next;
    }
  }
}

const cars = ['Audio', 'BMW', 'Mazda', 'Toyota'];
const list = new LinkedList();
for (let i = 0; i < cars.length; i++) {
  list.addToTail(cars[i])
}

list.remove('Audio')
list.addToTail('Kia')
list.addToTail('Lexus')
console.log(list.get('Mazda'));

【问题讨论】:

标签: javascript algorithm linked-list


【解决方案1】:

...并面临这样的问题:“我如何才能获得 O(1) 复杂度的 Node?”

你不能。链表总是需要一些级别的扫描。纯单链表是 O(n),IIRC。

我读过一些关于在链表中使用哈希表的文章。正常吗?

有一个映射结构对键进行散列以找到正确的“桶”并不罕见,其中“桶”是一个链表或类似的线性搜索容器,用于其键散列的所有条目相同的。基本上,get 就是:

  • 对密钥进行哈希处理
  • 通过哈希查找桶
  • 在存储桶中搜索键

不过,到那时,整体不再是链表,它更像是一张地图。即使是由哈希表支持的映射也不是 O(1),尽管它会比 O(n) 更好。

(我意识到你这样做是为了学习,但我必须指出 JavaScript 的原生 Map,它确实使用散列或(引用 spec)“......其他机制,平均而言,提供的访问时间与集合中的元素数量呈次线性关系。")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2015-12-21
    • 2016-11-05
    • 2021-07-11
    相关资源
    最近更新 更多