MCPcopy Index your code
hub / github.com/TheAlgorithms/JavaScript / addAt

Method addAt

Data-Structures/Linked-List/SinglyLinkedList.js:174–196  ·  view source on GitHub ↗
(index, element)

Source from the content-addressed store, hash-verified

172
173 // Adds the element at specified index
174 addAt(index, element) {
175 // Check if index is out of bounds of list
176 if (index > this.length || index < 0) {
177 throw new RangeError('Out of Range index')
178 }
179 if (index === 0) return this.addFirst(element)
180 if (index === this.length) return this.addLast(element)
181 let { currentIndex, currentNode } = this.initiateNodeAndIndex()
182 const node = new Node(element)
183
184 while (currentIndex !== index - 1) {
185 currentIndex++
186 currentNode = currentNode.next
187 }
188
189 // Adding the node at specified index
190 const tempNode = currentNode.next
191 currentNode.next = node
192 node.next = tempNode
193 // Incrementing the length
194 this.length++
195 return this.size()
196 }
197
198 // Removes the node at specified index
199 removeAt(index) {

Callers 1

Calls 4

addFirstMethod · 0.95
addLastMethod · 0.95
initiateNodeAndIndexMethod · 0.95
sizeMethod · 0.95

Tested by

no test coverage detected