在JavaScript中,链表是一种常见的数据结构,它可以用来存储数据集合,并且可以在集合中快速的插入和删除元素。
链表的一个主要优点是,在插入和删除操作时,不需要像数组那样移动大量的元素。链表中的每个元素都存储了下一个元素的地址,因此,对于插入和删除操作,我们只需要改变指针的指向即可。
以下是一个使用JavaScript实现单向链表的示例:
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
append(value) {
const newNode = new Node(value);
if (this.head === null) {
this.head = newNode;
} else {
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = newNode;
}
this.size++;
}
insert(position, value) {
if (position < 0 || position > this.size) return false;
const newNode = new Node(value);
if (position === 0) {
newNode.next = this.head;
this.head = newNode;
} else {
let index = 0;
let current = this.head;
let previous = null;
while (index++ < position) {
previous = current;
current = current.next;
}
newNode.next = current;
previous.next = newNode;
}
this.size++;
return true;
}
get(position) {
if (position < 0 || position >= this.size) return null;
let index = 0;
let current = this.head;
while (index++ < position) {
current = current.next;
}
return current.value;
}
remove(position) {
if (position < 0 || position >= this.size) return null;
let current = this.head;
if (position === 0) {
this.head = this.head.next;
} else {
let index = 0;
let previous = null;
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.size--;
return current.value;
}
}
export default LinkedList;
// 使用示例
import LinkedList from '文件地址'
const list = new LinkedList();