We need to create a function insert(data, position) that inserts data at given position in the linked list. We'll perform the following steps −
Here is an illustration of the same −
Now let's have a look at how we'll implement this −
insert(data, position = this.length) { let node = new this.Node(data); if (this.head === null) { this.head = node; this.length++; return this.head; } let iter = 1; let currNode = this.head; while (currNode.next != null && iter < position) { currNode = currNode.next; iter++; } node.next = currNode.next; currNode.next = node; this.length++; return node; }
Note that we've given position as the last element. This is because if you don’t provide a position, it'll be inserted at the end by default.
You can test this using −
let list = new LinkedList(); list.insert(10); list.insert(20); list.insert(30); list.insert(15, 2); list.display();
This will give the output −
10 -> 30 -> 15 -> 20 ->
As we can see all the elements are in the order we intended. We tried inserting 15 at the position after 2.