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();