Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of nodes in a linked list that may be circular

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.

like image 337
Tom Avatar asked Sep 18 '09 00:09

Tom


People also ask

How do you count the number of nodes in a circular linked list?

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.

What is count in circular linked list?

Given a circular linked list, count the number of nodes in it. For example, the output is 5 for the below list.

How can you tell if a Linkedlist is circular?

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.


2 Answers

The tortoise and hare algorithm can give you both the cycle length and the number of nodes before the cycle begins (λ and μ respectively).

like image 110
Artelius Avatar answered Sep 29 '22 09:09

Artelius


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.

like image 29
Igor ostrovsky Avatar answered Sep 29 '22 09:09

Igor ostrovsky