首页 > 编程语言 >javascript怎么实现链表?

javascript怎么实现链表?

时间:2024-08-26 23:22:55浏览次数:9  
标签:current head val 实现 javascript next 链表 节点

在JavaScript中实现链表通常涉及定义一个链表节点类(通常称为ListNode)和一个链表类(例如LinkedList),然后在这个链表类中实现各种操作链表的方法,如添加节点、删除节点、遍历链表等。

以下是使用JavaScript实现单向链表的一个基本示例:

链表节点类(ListNode)

首先,我们定义一个链表节点类,每个节点包含两部分:存储的数据(val)和指向下一个节点的指针(next)。

class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}

链表类(LinkedList)

然后,我们定义一个链表类,它包含一个指向链表头部节点的指针(head),以及一系列操作链表的方法。

class LinkedList {
constructor() {
this.head = null; // 初始链表为空
}
// 向链表尾部添加节点
append(val) {
let newNode = new ListNode(val);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
}
// 在链表头部添加节点
prepend(val) {
let newNode = new ListNode(val, this.head);
this.head = newNode;
}
// 删除链表中的节点(按值删除)
deleteNode(val) {
let current = this.head;
let previous = null;
if (current && current.val === val) {
this.head = current.next;
return;
}
while (current && current.val !== val) {
previous = current;
current = current.next;
}
if (current) {
previous.next = current.next;
current = null;
}
}
// 打印链表
printList() {
let current = this.head;
let listStr = "";
while (current) {
listStr += `${current.val} -> `;
current = current.next;
}
console.log(listStr + "null");
}
}
// 使用示例
let myList = new LinkedList();
myList.append(1);
myList.append(2);
myList.append(3);
myList.prepend(0);
myList.printList(); // 输出: 0 -> 1 -> 2 -> 3 -> null
myList.deleteNode(2);
myList.printList(); // 输出: 0 -> 1 -> 3 -> null

这个示例展示了如何在JavaScript中实现一个基本的单向链表,包括添加节点(尾部添加和头部添加)、删除节点(按值删除)和打印链表的方法。你可以根据需要扩展这个基础类,添加更多的功能,比如反转链表、查找节点、插入节点到指定位置等。

标签:current,head,val,实现,javascript,next,链表,节点
From: https://blog.csdn.net/m0_54007573/article/details/141575995

相关文章