← Back to challenges

Insert Element in Singly Linked List in a Given Index

JavaScriptHarddata_structuresalgorithmsarrays

Instructions

Create a method in a LinkedList class called insert that adds an element to the given index of the linked list and returns the added element. The LinkedList class is created for you. The first parameter is index and the second is element to be added.

Examples

Suppose data = [1, 2, 3]    // Just for explanation.

insert(10, 10) ➞ "Element cannot be added"
// index = 10 and element = 10
// Therefore, we cannot insert 10 because index > size of
// data and return msg.

insert(-1, 10) ➞ "Element cannot be added"
// index = -1 and element = 10
// Therefore, we cannot insert 10 because index is negative
// (less than zero) return msg.

insert(0, 0) ➞ 0
// index = 0 and element = 0
// Therefore, we insert 0 at index 0 (beginning of the linked
// list) and return element.

Notes

Element is an integer.

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.