educative.io

Doubt in the insert_after_node method in singly linked list

In the code, inside the insert_after_node method, there is this line at the end - llist.insert_after_node(llist.head.next,“D”). llist.head.next points to 2nd location. What if we wanted to insert after 3rd node, how to give the location of it as the first argument in the above line?

First Approach is that we can give a specific position of node and set a counter to that position and then insert after that position.Here is a code for it:
position = 3
counter = 1
cur_node1 = llist.head
while (counter != position):
cur_node1=cur_node1.next
counter = counter + 1

list.insert_after_node(cur_node1, “D”)
Its working perfectly fine. Function calling will come outside the while loop.
The 2nd approach is using next of head
llist.insert_after_node(llist.head.next.next, “D”)
If you want to insert at 3rd position
But the beat way is to use a loop