diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index ba7d0e3e..c898b5bd 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -269,4 +269,25 @@ export default class LinkedList { return this; } + + /** + * @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; + } } diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index 6ac41ddf..ae622502 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -157,9 +157,7 @@ describe('LinkedList', () => { const nodeValue1 = { value: 1, key: 'key1' }; const nodeValue2 = { value: 2, key: 'key2' }; - linkedList - .append(nodeValue1) - .prepend(nodeValue2); + linkedList.append(nodeValue1).prepend(nodeValue2); const nodeStringifier = (value) => `${value.key}:${value.value}`; @@ -174,9 +172,7 @@ describe('LinkedList', () => { linkedList.append(1); expect(linkedList.find({ value: 1 })).toBeDefined(); - linkedList - .append(2) - .append(3); + linkedList.append(2).append(3); const node = linkedList.find({ value: 2 }); @@ -192,7 +188,9 @@ describe('LinkedList', () => { .append({ value: 2, key: 'test2' }) .append({ value: 3, key: 'test3' }); - const node = linkedList.find({ callback: (value) => value.key === 'test2' }); + const node = linkedList.find({ + callback: (value) => value.key === 'test2', + }); expect(node).toBeDefined(); expect(node.value.value).toBe(2); @@ -258,10 +256,7 @@ describe('LinkedList', () => { const linkedList = new LinkedList(); // Add test values to linked list. - linkedList - .append(1) - .append(2) - .append(3); + linkedList.append(1).append(2).append(3); expect(linkedList.toString()).toBe('1,2,3'); expect(linkedList.head.value).toBe(1); @@ -279,4 +274,14 @@ describe('LinkedList', () => { expect(linkedList.head.value).toBe(1); expect(linkedList.tail.value).toBe(3); }); + + 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); + }); });