In: Computer Science
We can use linked list conpect to achive this.
Here is code:
// make a class called node.
class Node {
// which has data and next node
constructor(data) {
this.data = data;
this.next = null;
}
}
// alternative of array
class SingleLinkedList {
constructor() {
this.head = null;
this.itemCount = 0; // size of list
}
addBefore(data, indexAt) {
if (indexAt <= this.itemCount) {
let node = new Node(data); // create node
let current, previous;
current = this.head;
if (indexAt != 0) {
current = this.head;
for (let index = 0; index < indexAt; index++) {
previous = current;
current = current.next;
}
// adding an node at the position
node.next = current;
previous.next = node;
} else {
node.next = this.head;
this.head = node;
}
this.itemCount++;
}
}
}
var ll = new SingleLinkedList();
ll.addBefore(10, 0); // add 0th position [10]
ll.addBefore(20, 0); // add 0th position [20, 10]
ll.addBefore(30, 1); // add 0th position [20, 30, 10]
ll.addBefore(40, 0); // add 0th position [40, 20, 30, 10]
Output: