diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index 4e82ab0d..7d330f7b 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -21,7 +21,13 @@ export default class LinkedList { */ prepend(value) { // Make new node to be a head. - this.head = new LinkedListNode(value, this.head); + const newNode = new LinkedListNode(value, this.head); + this.head = newNode; + + // If there is no tail yet let's make new node a tail. + if (!this.tail) { + this.tail = newNode; + } return this; } diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index 61f018fe..384e44fa 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -21,10 +21,14 @@ describe('LinkedList', () => { it('should prepend node to linked list', () => { const linkedList = new LinkedList(); - linkedList.append(1); linkedList.prepend(2); + expect(linkedList.head.toString()).toBe('2'); + expect(linkedList.tail.toString()).toBe('2'); - expect(linkedList.toString()).toBe('2,1'); + linkedList.append(1); + linkedList.prepend(3); + + expect(linkedList.toString()).toBe('3,2,1'); }); it('should delete node by value from linked list', () => {