Given a singly linked list, write a function to find the $\sqrt[]{n}$ element, where n is the number of elements in the list. Assume the value of n is not known in advance.
The simple method is to first find the total number of nodes present in the linked list, then find the value of floor(sqrt(n)) where n is the total number of nodes. Then traverse from the first node in the list to this position and return the node at this position.
Method 2 - One Iteration Solution Using Tortoise and Hare Pointers#
√n’th node in a singly linked list where n is the number of elements in the list, but n is not known in advance.
Use two pointers: one for traversing the list and another for keeping track of the √nth node
As we traverse the list, count the number of nodes.
Update the √n’th pointer whenever we’ve traversed a new √n’th position
Initialize two counters i and j both to 1 and a pointer sqrtn to NULL to traverse til the required position is reached.
Start traversing the list using head node until the last node is reached.
While traversing check if the value of j is equal to sqrt(i). If the value is equal increment both i and j and sqrtn to point sqrtn->next otherwise increment only i.
Now, when we will reach the last node of list i will contain value of n, j will contain value of sqrt(i) and sqrtn will point to node at jth position.