Skip to content

Commit 6f6fecc

Browse files
committed
add the indexOf() method
1 parent 9f0cad5 commit 6f6fecc

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/data-structures/linked-list/LinkedList.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,4 +288,25 @@ export default class LinkedList {
288288

289289
return res;
290290
}
291+
292+
/**
293+
* Find the index of the value.
294+
* @param {*} value
295+
* @returns {number}
296+
*/
297+
indexOf(value) {
298+
if (this.getSize() === 0) return -1; // check if the size of list is 0 return -1;
299+
let currNode = this.head;
300+
let index = 0;
301+
302+
// Iterate the list to find the value.
303+
while (currNode) {
304+
if (currNode.value === value) return index;
305+
currNode = currNode.next;
306+
index++;
307+
}
308+
309+
// if the value dont exist:
310+
return -1;
311+
}
291312
}

0 commit comments

Comments
 (0)