js(JavaScript)数据结构之链表(Linked List)
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(index, value) {
if (index >= 0 && index <= this.size) {
const newNode = new Node(value);
if (index === 0) {
newNode.next = this.head;
this.head = newNode;
} else {
let current = this.head;
let previous = null;
let count = 0;
while (count < index) {
previous = current;
current = current.next;
count++;
}
newNode.next = current;
previous.next = newNode;
}
this.size++;
return true;
}
return false;
}
// 移除特定位置的元素
removeAt(index) {
if (index >= 0 && index < this.size) {
let current = this.head;
if (index === 0) {
this.head = current.next;
} else {
let previous = null;
let count = 0;
while (count < index) {
previous = current;
current = current.next;
count++;
}
previous.next = current.next;
}
this.size--;
return current.value;
}
return null;
}
// 移除特定值的元素
remove(value) {
let index = this.indexOf(value);
return this.removeAt(index);
}
// 查找特定值的元素索引
indexOf(value) {
let current = this.head;
let index = 0;
while (current) {
if (current.value === value) {
return index;
}
index++;
current = current.next;
}
return -1;
}
// 打印链表元素
print() {
let current = this.head;
while (current) {
console.log(current.value);
current = current.next;
}
}
}
// 示例使用链表
const linkedList = new LinkedList();
linkedList.append(10);
linkedList.append(20);
linkedList.append(30);
linkedList.insert(1, 15);
linkedList.removeAt(2);
linkedList.print(); // 输出: 10 15 30
这段代码定义了一个简单的
评论已关闭