
链表是一种线性数据结构,其中每个元素(也称为节点)包含一个数据值和对列表中下一个节点的引用。链表上的一种常见操作是搜索特定元素。这涉及遍历列表并将每个节点的数据值与目标元素进行比较,直到找到匹配项。
这是我们将在整篇文章中使用的链接列表的示例 -
10 -> 20 -> 30 -> 40 -> 空
在此链表中,每个节点都包含一个值,箭头指示序列中的下一个节点。该列表从包含值 10 的头节点开始,以包含值 40 并指向 null 的尾节点结束。我们将使用这个链表来演示如何使用 JavaScript 在链表中搜索元素。
立即学习“Java免费学习笔记(深入)”;
让我们看看下面的例子 -
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 步 - 定义一个名为 - add 的方法到以值作为参数的 LinkedList 类。 add 方法应该使用给定值创建一个新节点并将其添加到链表的末尾。
第 4 步 - 为 LinkedList 类定义一个名为“remove”的方法,该方法采用一个值作为参数。 remove 方法应该删除链表中具有给定值的第一个节点。
第 5 步 - 为 LinkedList 类定义一个名为 search 的方法,该方法将值作为参数。 search 方法应该返回给定值的链表中的第一个节点,如果没有找到节点则返回 null。
第6步 - 为LinkedList类定义一个名为reverse的方法,用于反转链表中节点的顺序。
下面的程序定义了一个 Node 类和一个 LinkedList 类。 Node 类使用给定的数据值和对列表中下一个节点的引用创建一个新节点。 LinkedList 类创建一个新的链表,其头节点最初指向 null,并且 size 属性设置为 0。 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循环遍历链表,并将每个节点中的数据元素与正在查找的元素进行比较。如果找到该元素,则程序返回该节点的索引,如果未找到该元素,则程序返回“Element not find”。
以上就是用于在链接列表中搜索元素的 JavaScript 程序的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号