diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index ba7d0e3ee1..39de5b4671 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -75,6 +75,9 @@ export default class LinkedList { if (currentNode) { newNode.next = currentNode.next; currentNode.next = newNode; + if (this.tail === currentNode) { + 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..bf411e24a5 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -47,6 +47,18 @@ describe('LinkedList', () => { expect(linkedList.toString()).toBe('1,4,2,3,10'); }); + it('should insert and maintain head and tail', () => { + const linkedList = new LinkedList(); + + linkedList.insert(2, 0); + linkedList.insert(3, 1); + linkedList.insert(4, 2); + + expect(linkedList.toString()).toBe('2,3,4'); + expect(linkedList.head.toString()).toBe('2'); + expect(linkedList.tail.toString()).toBe('4'); + }); + it('should delete node by value from linked list', () => { const linkedList = new LinkedList();