链表是一种线性数据结构,其中每个元素(也称为节点)包含一个数据值和对列表中下一个节点的引用。链表上的一种常见操作是搜索特定元素。这涉及遍历列表并将每个节点的数据值与目标元素进行比较,直到找到匹配项。
这是我们将在整篇文章中使用的链接列表的示例 –
10 -> 20 -> 30 -> 40 -> 空
在此链表中,每个节点都包含一个值,箭头指示序列中的下一个节点。该列表从包含值 10 的头节点开始,以包含值 40 并指向 null 的尾节点结束。我们将使用这个链表来演示如何使用 JavaScript 在链表中搜索元素。
立即学习“Java免费学习笔记(深入)”;
让我们看看下面的例子 –
Linked list: 10 -> 20 -> 30 -> 40 -> nullInput: 40Output: Element found at index 3Input: 10Output: Element found at index 0Input: nullOutput: 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的方法,用于反转链表中节点的顺序。
示例:使用 JavaScript 实现上述算法
下面的程序定义了一个 Node 类和一个 LinkedList 类。 Node 类使用给定的数据值和对列表中下一个节点的引用创建一个新节点。 LinkedList 类创建一个新的链表,其头节点最初指向 null,并且 size 属性设置为 0。 add 方法将新节点添加到链表的末尾。 search方法遍历链表,如果找到则返回该元素的索引,如果没有找到则返回一条消息。最后,程序创建一个新的链表,向其中添加元素,并搜索特定元素。
// Define the Node class for a singly linked listclass Node { constructor(data) { this.data = data; this.next = null; }}// Define the LinkedList classclass 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 listconst ll = new LinkedList();// Add elements to the linked listll.add(10);ll.add(20);ll.add(30);ll.add(40);ll.add(50);// Search for an element in the linked listconst result = ll.search(30);console.log(result);
登录后复制
结论
使用 JavaScript 在链接列表中搜索元素的程序涉及创建一个“LinkedList”类,该类定义向列表添加元素以及在列表中搜索元素的方法。程序使用while循环遍历链表,并将每个节点中的数据元素与正在查找的元素进行比较。如果找到该元素,则程序返回该节点的索引,如果未找到该元素,则程序返回“Element not find”。
以上就是用于在链接列表中搜索元素的 JavaScript 程序的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2692166.html