From 6b1c5175bae2febf5dac844f8adddb23551366da Mon Sep 17 00:00:00 2001 From: Darkslayer3324j Date: Sat, 19 Sep 2026 21:55:32 +0500 Subject: [PATCH] Fix LinkedList.insert not updating the tail when inserting after the last node insert(value, index) with index equal to the list length linked the new node after the current tail but left this.tail pointing at the old last node, so a following append() overwrote the inserted node and it was lost. Update the tail in that case and add a test. Co-Authored-By: Claude Sonnet 5 --- src/data-structures/linked-list/LinkedList.js | 6 ++++++ .../linked-list/__test__/LinkedList.test.js | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index ba7d0e3ee1..b4f6eba9d5 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -75,6 +75,12 @@ export default class LinkedList { if (currentNode) { newNode.next = currentNode.next; currentNode.next = newNode; + + // If the new node was linked after the current tail, it is the new tail. + // Otherwise the next append() would overwrite it and drop the node. + if (currentNode === this.tail) { + this.tail = newNode; + } } else { if (this.tail) { this.tail.next = newNode; diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index 6ac41ddf05..b6bfcfe436 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -47,6 +47,22 @@ describe('LinkedList', () => { expect(linkedList.toString()).toBe('1,4,2,3,10'); }); + it('should update the tail when inserting after the last node', () => { + const linkedList = new LinkedList(); + + linkedList.append(1).append(2); + linkedList.insert(3, 2); + + expect(linkedList.tail.value).toBe(3); + expect(linkedList.toString()).toBe('1,2,3'); + + linkedList.append(4); + + expect(linkedList.toString()).toBe('1,2,3,4'); + expect(linkedList.deleteTail().value).toBe(4); + expect(linkedList.deleteTail().value).toBe(3); + }); + it('should delete node by value from linked list', () => { const linkedList = new LinkedList();