JavaScript 链表中搜索元素的程序
链表是一种线性数据结构,其中每个元素(也称为节点)包含一个数据值和指向列表中下一个节点的引用。链表上一个常见的操作是搜索特定元素。这涉及遍历列表并将每个节点的数据值与目标元素进行比较,直到找到匹配项。
以下是一个我们将在这整篇文章中使用的链表示例:
10 -> 20 -> 30 -> 40 -> null
在此链表中,每个节点都包含一个值,箭头指示序列中的下一个节点。列表以头节点开始,头节点包含值 10,并以尾节点结束,尾节点包含值 40 并指向 null。我们将使用此链表来演示如何使用 JavaScript 在链表中搜索元素。
让我们看看下面的例子:
Linked list: 10 -> 20 -> 30 -> 40 -> null Input: 40 Output: Element found at index 3 Input: 10 Output: Element found at index 0 Input: null Output: Element not found
现在让我们讨论在 JavaScript 中创建链表的算法。
算法
步骤 1 - 定义一个具有两个属性的 Node 类:value 和 next。value 属性表示存储在节点中的数据,next 属性是指向链表中下一个节点的引用。
步骤 2 - 定义一个具有三个属性的 LinkedList 类:head、tail 和 length。head 属性表示链表中的第一个节点,tail 属性表示链表中的最后一个节点,length 属性表示链表中节点的数量。
步骤 3 - 在 LinkedList 类中定义一个名为 add 的方法,该方法将一个值作为参数。add 方法应该创建一个具有给定值的新节点并将其添加到链表的末尾。
步骤 4 - 在 LinkedList 类中定义一个名为 remove 的方法,该方法将一个值作为参数。remove 方法应该删除链表中第一个具有给定值的节点。
步骤 5 - 在 LinkedList 类中定义一个名为 search 的方法,该方法将一个值作为参数。search 方法应该返回链表中第一个具有给定值的节点,如果未找到节点则返回 null。
步骤 6 - 在 LinkedList 类中定义一个名为 reverse 的方法,该方法反转链表中节点的顺序。
示例:使用 JavaScript 实现上述算法
以下程序定义了一个 Node 类和一个 LinkedList 类。Node 类使用给定的数据值和指向列表中下一个节点的引用创建一个新节点。LinkedList 类使用一个最初指向 null 的头节点和一个设置为 0 的 size 属性创建一个新的链表。add 方法将一个新节点添加到链表的末尾。search 方法遍历链表,如果找到元素则返回该元素的索引,或者返回一条消息,指示未找到该元素。最后,程序创建一个新的链表,向其中添加元素,并搜索特定元素。
// Define the Node class for a singly linked list
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Define the LinkedList class
class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}
// Add an element to the linked list
add(element) {
const node = new Node(element);
// If the linked list is empty, set the new node as the head
if (this.head === null) {
this.head = node;
} else {
// Traverse to the end of the linked list and add the new node
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
}
this.size++;
}
// Search for an element in the linked list
search(element) {
let current = this.head;
let index = 0;
// Traverse through the linked list until the element is found
while (current !== null) {
if (current.data === element) {
return `Element found at index ${index}`;
}
current = current.next;
index++;
}
return "Element not found";
}
}
// Create a new linked list
const ll = new LinkedList();
// Add elements to the linked list
ll.add(10);
ll.add(20);
ll.add(30);
ll.add(40);
ll.add(50);
// Search for an element in the linked list
const result = ll.search(30);
console.log(result);
结论
使用 JavaScript 在链表中搜索元素的程序涉及创建 'LinkedList' 类,该类定义了向列表中添加元素和在列表中搜索元素的方法。该程序使用 while 循环遍历链表,并将每个节点中的数据元素与要搜索的元素进行比较。如果找到该元素,则程序返回该节点的索引,如果未找到该元素,则程序返回“未找到元素”。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP