返回
JS 单链表:理解链表结构和基本操作
前端
2024-01-04 16:40:20
什么是单链表?
单链表是一种线性数据结构,由一组节点组成,每个节点包含一个数据项和一个指向下一个节点的指针。链表中的第一个节点称为头节点,最后一个节点称为尾节点。单链表中的节点可以存储任何类型的数据,包括字符串、数字、对象等。
单链表的基本操作
单链表的基本操作包括:
- 添加节点:在链表的开头或结尾添加一个新的节点。
- 删除节点:从链表中删除一个指定的节点。
- 查找节点:在链表中查找一个包含特定数据的节点。
- 遍历链表:从头节点开始,逐个访问链表中的所有节点。
在 JavaScript 中实现单链表
我们可以使用 JavaScript 中的 class
来实现单链表。以下是一个简单的单链表类:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.count = 0;
}
// 在链表头部添加一个新节点
push(data) {
const newNode = new Node(data);
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.count++;
}
// 在链表尾部添加一个新节点
append(data) {
const newNode = new Node(data);
if (this.isEmpty()) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.count++;
}
// 从链表中删除一个节点
remove(data) {
if (this.isEmpty()) {
return;
}
let current = this.head;
let previous = null;
while (current) {
if (current.data === data) {
if (previous) {
previous.next = current.next;
} else {
this.head = current.next;
}
if (current === this.tail) {
this.tail = previous;
}
this.count--;
break;
}
previous = current;
current = current.next;
}
}
// 在链表中查找一个节点
find(data) {
if (this.isEmpty()) {
return null;
}
let current = this.head;
while (current) {
if (current.data === data) {
return current;
}
current = current.next;
}
return null;
}
// 遍历链表
traverse() {
if (this.isEmpty()) {
return;
}
let current = this.head;
while (current) {
console.log(current.data);
current = current.next;
}
}
// 判断链表是否为空
isEmpty() {
return this.count === 0;
}
}
单链表的应用场景
单链表在 JavaScript 中有很多应用场景,包括:
- 存储有序数据:单链表可以用来存储有序数据,比如学生成绩、商品列表等。
- 作为队列或栈的数据结构:单链表可以作为队列或栈的数据结构来使用。
- 实现广度优先搜索或深度优先搜索算法:单链表可以用来实现广度优先搜索或深度优先搜索算法。
总结
单链表是一种简单但强大的数据结构,在 JavaScript 中有很多应用场景。通过了解单链表的基础知识和基本操作,我们可以更好地理解 JavaScript 中的数据结构,并将其应用到我们的项目中。