From f5639497d84c00a5138437968f14f9231c0fbb19 Mon Sep 17 00:00:00 2001 From: harishnanthan Date: Sat, 4 Mar 2023 11:34:31 +0530 Subject: [PATCH] added length for the linked list to solve the insert method problem --- src/data-structures/linked-list/LinkedList.js | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index ba7d0e3e..b8f7f298 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -12,6 +12,8 @@ export default class LinkedList { /** @var LinkedListNode */ this.tail = null; + this.length = 0; + this.compare = new Comparator(comparatorFunction); } @@ -29,6 +31,9 @@ export default class LinkedList { this.tail = newNode; } + // once node added, modify the length the list + this.length++; + return this; } @@ -51,6 +56,9 @@ export default class LinkedList { this.tail.next = newNode; this.tail = newNode; + // once node added, modify the length the list + this.length++; + return this; } @@ -63,6 +71,8 @@ export default class LinkedList { const index = rawIndex < 0 ? 0 : rawIndex; if (index === 0) { this.prepend(value); + } else if (index === this.length) { + this.append(value); } else { let count = 1; let currentNode = this.head; @@ -85,6 +95,10 @@ export default class LinkedList { } } } + + // once node added, modify the length the list + this.length++; + return this; } @@ -125,6 +139,9 @@ export default class LinkedList { this.tail = currentNode; } + // once node added, modify the length the list + this.length--; + return deletedNode; } @@ -186,6 +203,9 @@ export default class LinkedList { this.tail = currentNode; + // once node added, modify the length the list + this.length--; + return deletedTail; } @@ -206,6 +226,9 @@ export default class LinkedList { this.tail = null; } + // once node added, modify the length the list + this.length--; + return deletedHead; }