【发布时间】: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'));
【问题讨论】:
-
O(n) 获取链表元素的性能是预期的。
-
普通链表是 O(n) 获取一个元素。看看->stackoverflow.com/questions/40718116/…
标签: javascript algorithm linked-list