April 2018
Beginner to intermediate
426 pages
10h 19m
English
Next, we are going to implement the insert method. This method provides you with the capability to insert an element at any position. Let's take a look at its implementation:
insert(element, index) { if (index >= 0 && index <= this.count) { // {1} const node = new Node(element); if (index === 0) { // add on first position const current = this.head; node.next = current; // {2} this.head = node; } else { const previous = this.getElementAt(index - 1); // {3} const current = previous.next; // {4} node.next = current; // {5} previous.next = node; // {6} } this.count++; // update size of list return true; } return false; // {7}}
As we are handling positions (indexes), we need to check the out-of-bound values ...