search
HomeWeb Front-endJS TutorialJavaScript program for searching for elements in a linked list

用于在链接列表中搜索元素的 JavaScript 程序

A linked list is a linear data structure in which each element (also called a node) contains a data value and a reference to the next node in the list. A common operation on a linked list is to search for a specific element. This involves walking through the list and comparing each node's data value to the target element until a match is found.

This is an example of a linked list we will use throughout this article -

10 -> 20 -> 30 -> 40 -> Empty

In this linked list, each node contains a value, and the arrow indicates the next node in the sequence. The list starts with the head node, which contains the value 10, and ends with the tail node, which contains the value 40 and points to null. We will use this linked list to demonstrate how to search for an element in a linked list using JavaScript.

Let’s look at the following example -

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

Now let’s discuss the algorithm for creating linked lists in JavaScript.

algorithm

Step 1 - Define a Node class with two properties: value and next. The value attribute represents the data stored in the node, and the next attribute is a reference to the next node in the linked list.

Step 2 - Define a LinkedList class with three properties: head, tail and length. The head attribute represents the first node in the linked list, the tail attribute represents the last node in the linked list, and the length attribute represents the number of nodes in the linked list.

Step 3 - Define a method named - add to the LinkedList class that takes a value as a parameter. The add method should create a new node with the given value and add it to the end of the linked list.

Step 4 - Define a method called "remove" for the LinkedList class that takes a value as a parameter. The remove method should remove the first node with a given value in the linked list.

Step 5 - Define a method called search for the LinkedList class that takes a value as a parameter. The search method should return the first node in the linked list with the given value, or null if the node is not found.

Step 6 - Define a method named reverse for the LinkedList class, which is used to reverse the order of nodes in the linked list.

Example: Using JavaScript to implement the above algorithm

The following program defines a Node class and a LinkedList class. The Node class creates a new node using the given data value and a reference to the next node in the list. The LinkedList class creates a new linked list with the head node initially pointing to null and the size property set to 0. The add method adds a new node to the end of the linked list. The search method traverses the linked list and returns the index of the element if found, or a message if not found. Finally, the program creates a new linked list, adds elements to it, and searches for a specific element.

// 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); 

in conclusion

The procedure for searching for elements in a linked list using JavaScript involves creating a "LinkedList" class that defines methods for adding elements to the list and for searching for elements in the list. The program uses a while loop to traverse the linked list and compare the data element in each node to the element it is looking for. If the element is found, the program returns the index of the node, if the element is not found, the program returns "Element not find".

The above is the detailed content of JavaScript program for searching for elements in a linked list. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.