单向链表是一种线性数据结构,其中每个元素都包含一个指向下一个元素的指针。在JavaScript中,可以通过定义节点类和链表类来实现单向链表。以下是实现单向链表的基础概念、优势、类型、应用场景以及相关代码示例:
以下是JavaScript实现单向链表的示例代码:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// 在链表末尾添加节点
append(data) {
const node = new Node(data);
if (this.head === null) {
this.head = node;
} else {
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
}
this.size++;
}
// 在指定位置插入节点
insertAt(data, index) {
if (index < 0 || index > this.size) {
return console.log("Index out of bounds");
}
const node = new Node(data);
if (index === 0) {
node.next = this.head;
this.head = node;
} else {
let current = this.head;
let previous;
let count = 0;
while (count < index) {
previous = current;
current = current.next;
count++;
}
node.next = current;
previous.next = node;
}
this.size++;
}
// 删除指定位置的节点
removeAt(index) {
if (index < 0 || index >= this.size) {
return console.log("Index out of bounds");
}
let current = this.head;
if (index === 0) {
this.head = current.next;
} else {
let previous;
let count = 0;
while (count < index) {
previous = current;
current = current.next;
count++;
}
previous.next = current.next;
}
this.size--;
return current.data;
}
// 打印链表
printList() {
let current = this.head;
let str = "";
while (current !== null) {
str += current.data + " ";
current = current.next;
}
console.log(str);
}
}
// 示例用法
const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.insertAt(15, 1);
list.printList(); // 输出: 10 15 20 30
list.removeAt(2);
list.printList(); // 输出: 10 15 30
通过上述代码示例和解释,你可以更好地理解单向链表的实现及其应用。
领取专属 10元无门槛券
手把手带您无忧上云