Array 实现链表(双向、单向)
1. C++ list 与 forward_list 简介
list 与 forward_list 简介2. JavaScript 的 Array 代替 list
Array 代替 listlet arr = [1, 2, 3, 4];
arr.push(5); // 添加元素到末尾
arr.shift(); // 删除头部元素
arr.splice(1, 0, 10); // 在索引1位置插入元素103. 使用 JavaScript 自定义类模拟链表
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
}
// 在链表末尾添加元素
append(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
}
// 删除链表中的第一个元素
removeHead() {
if (this.head) {
this.head = this.head.next;
}
}
// 打印链表
printList() {
let current = this.head;
let list = [];
while (current) {
list.push(current.value);
current = current.next;
}
console.log(list.join(' -> '));
}
}
// 使用单向链表
let list = new SinglyLinkedList();
list.append(1);
list.append(2);
list.append(3);
list.printList(); // 输出: 1 -> 2 -> 3
list.removeHead();
list.printList(); // 输出: 2 -> 34. 总结
Last updated