educative.io

Educative

How is the last node connecting back?

Hello, For the linked list cycle problem. How are you connecting back from the last node? It appears that in some examples it reaches the end and then links to the head but in other examples it links somewhere in the middle of the list.

Thanks.

The code creates a cycle by connecting the last node of the list to some node within the list based on the pos array. If pos[i] is -1, it means there’s no cycle, and the last node is simply connected to null. Otherwise, it connects the last node to the node at index pos[i] in the list, creating a cycle.

So, in some examples, the cycle is created by connecting the last node back to the head of the list, while in other examples, it’s connected to some node in the middle of the list, as dictated by the pos array.