Here is the problem, it is from Sedgwick's excellent Algorithms in Java (q 3.54)
Given a link to a node in a singly linked list that contains no null links (i.e. each node either links to itself or another node in the list) determine the number of different nodes without modifying any of the nodes and using no more than constant memory space.
How do you do it? scan through the list once using the hare and tortoise algorithm to work out whether it is circular in any way, and then scan through again to work out where the list becomes circular, then scan through again counting the number of nodes to this position? sounds a bit brute-force to me, I guess there is much more elegant solution.
countNodes() will count the number of nodes present in the list. Define new node current which will point to the head node. Traverse through the list to count the nodes by making the current node to point to next node in the list till current points to head again.
Given a circular linked list, count the number of nodes in it. For example, the output is 5 for the below list.
A linked list is called circular if the next pointer of the last node of the list points back to the first node. If this pointer points to NULL or any other previous nodes (other than the first node), then the linked list won't be called circular.
The tortoise and hare algorithm can give you both the cycle length and the number of nodes before the cycle begins (λ and μ respectively).
The most elegant solution is Floyd's cycle-finding algorithm: http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare
It runs in O(N) time, and only constant amount of memory is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With