diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index 71c2b497..310af779 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -54,6 +54,40 @@ export default class LinkedList { return this; } + /** + * @param {*} value + * @param {*} index + * @return {LinkedList} + */ + insert(value, index) { + index = index < 0 ? 0 : index; + if (index === 0) { + this.prepend(value); + } else { + let count = 1; + let currentNode = this.head; + const newNode = new LinkedListNode(value); + while (currentNode) { + if (count === index) break; + currentNode = currentNode.next; + count++; + } + if (currentNode) { + newNode.next = currentNode.next; + currentNode.next = newNode; + } else { + if (this.tail) { + this.tail.next = newNode; + this.tail = newNode; + } else { + this.head = newNode; + this.tail = newNode; + } + } + } + return this; + } + /** * @param {*} value * @return {LinkedListNode} diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index f4eb83e2..cc9440f1 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -32,6 +32,21 @@ describe('LinkedList', () => { expect(linkedList.toString()).toBe('3,2,1'); }); + it('should insert node to linked list', () => { + const linkedList = new LinkedList(); + + linkedList.insert(4, 3); + expect(linkedList.head.toString()).toBe('4'); + expect(linkedList.tail.toString()).toBe('4'); + + linkedList.insert(3, 2); + linkedList.insert(2, 1); + linkedList.insert(1, -7); + linkedList.insert(10, 9); + + expect(linkedList.toString()).toBe('1,4,2,3,10'); + }) + it('should delete node by value from linked list', () => { const linkedList = new LinkedList();