Skip to content

Linked list methods #2066

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 80 additions & 1 deletion src/data-structures/linked-list/LinkedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,9 @@ export default class LinkedList {
* @return {string}
*/
toString(callback) {
return this.toArray().map((node) => node.toString(callback)).toString();
return this.toArray()
.map((node) => node.toString(callback))
.toString();
}

/**
Expand Down Expand Up @@ -269,4 +271,81 @@ export default class LinkedList {

return this;
}

/**
* Get us the size of the link;
* @returns {number}
*/
getSize() {
let res = 0;
let currNode = this.head;

// Iterate the entire list.
while (currNode) {
res++;
currNode = currNode.next;
}

return res;
}

/**
* Find the index of the value.
* @param {*} value
* @returns {number}
*/
indexOf(value) {
if (this.getSize() === 0) return -1; // check if the size of list is 0 return -1;
let currNode = this.head;
let index = 0;

// Iterate the list to find the value.
while (currNode) {
if (currNode.value === value) return index;
currNode = currNode.next;
index++;
}

// if the value dont exist:
return -1;
}

/**
* Find the value of specified index.
* @param {number} index
* @returns {*}
*/
at(index) {
// check if the index not exist
if (index < 0 || index > this.getSize()) return undefined;
let i = 0;
let currNode = this.head;

// Iterate the list to find the index.
while (i < index) {
currNode = currNode.next;
i++;
}

return currNode.value;
}

/**
* Print the entire list.
*/
print() {
if (this.getSize() === 0) return ''; // check if the list size is zero;
let res = '';
let currNode = this.head;

// Iterate the list to add values to res variable
while (currNode) {
res += `${currNode.value} ==> `;
currNode = currNode.next;
}

res += `null`;

console.log(res);
}
}