JavaScript Exercises: Get index of an given element in a Singly Linked list
JavaScript Singly Linked List: Exercise-17 with Solution
Write a JavaScript program to get the index of an element in a Singly Linked list.
Sample Solution:
JavaScript Code:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class SinglyLinkedList {
constructor(Head = null) {
this.Head = Head;
}
add(newNode){
let node = this.Head;
if(node==null){
this.Head = newNode;
return;
}
while (node.next) {
node = node.next;
}
node.next = newNode;
}
index_of(el) {
let index = 0;
let node = this.Head;
while (node) {
if (node.data === el) {
return index;
}
node = node.next;
index++;
}
return -1;
}
displayList(){
let node = this.Head;
var str = ""
while (node) {
str += node.data + "->";
node = node.next;
}
str += "NULL"
console.log(str);
}
}
let numList = new SinglyLinkedList();
numList.add(new Node(12));
numList.add(new Node(13));
numList.add(new Node(14));
numList.add(new Node(15));
numList.add(new Node(14));
numList.add(new Node(16));
console.log("Singly Linked list:")
numList.displayList();
result = numList.index_of(12);
console.log("Index of 12 in the said link list: "+result);
result = numList.index_of(13);
console.log("Index of 13 in the said link list: "+result);
result = numList.index_of(14);
console.log("Index of 14 in the said link list: "+result);
result = numList.index_of(16);
console.log("Index of 16 in the said link list: "+result);
Sample Output:
Singly Linked list: 12->13->14->15->14->16->NULL Index of 12 in the said link list: 0 Index of 13 in the said link list: 1 Index of 14 in the said link list: 2 Index of 16 in the said link list: 5
Flowchart:

Live Demo:
See the Pen javascript-singly-linked-list-exercise-17 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Singly Linked List Previous: Convert a Singly Linked list into a string.
Singly Linked List Next: Check if an element is present in the Singly Linked list.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
JavaScript: Tips of the Day
Initialize an Array with Values
We can use the Array constructor with the fill method to create an array and fill it with items. For instance, we can write:
Array(20).fill(10)
to create an array with 20 empty slots, then fill the slots with 10.
Ref: https://bit.ly/3mp5NgH
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises