javascript-algorithms
javascript-algorithms copied to clipboard
Add 'size()' method in linked list data structure and also written te…
Update file src/data-structures/linked-list/LinkedList.js and src/data-structures/linked-list/test/LinkedList.test.js
- src/data-structures/linked-list/LinkedList.js
Before
After
/**
* @returns {Number}
*/
size() {
// If head is null the size of linked list will be -1 or 0, So here we return -1.
if (!this.head) {
return -1;
}
let size = 0;
let currentNode = this.head;
// Traverse to the linked list and update the size.
while (currentNode) {
size += 1;
currentNode = currentNode.next;
}
return size;
}
- src/data-structures/linked-list/test/LinkedList.test.js
Before
After
it('should return the size of linked list', () => {
const linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
linkedList.append(3);
expect(linkedList.size()).toBe(3);
});