Add 'size()' method in linked list data structure and also written test case for it.

This commit is contained in:
bhaveshmhadse 2023-06-27 13:28:45 +05:30
parent 8c5e5f4f0d
commit 027dace411
2 changed files with 37 additions and 11 deletions

View File

@ -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;
}
}

View File

@ -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);
});
});