I don’t think I think this is a linked list. LinkedLists usually end with a null pointer or a pointer pointing to a trailing character. I.e start -> A -> B -> C -> end. : . I think it will be a certain kind of graph.
To find the total number of nodes in a graph, I would do the following:
List visited;
List toVisit;
toVisit.add(A);
while(toVisit is not empty){
Node current = visited.remove();
Array <Node> links = current.getLinks();
for(int i=0; i<links.size(); i++){
if(!visited.contains(links[i])){
toVisit.add(links[i]);
}
visited.add(current);
}
}
return visited.size();
, ( ...):
A ---> ... ---> C -----> D -----> E
Λ |
| |
| V
... <----- G <--- F
:
List visited;
Node current = firstNode;
while(!visited.contains(firstNode)){
Node next = current.getNext();
visited.add(current);
current=next;
}
int currentIndex = visited.indexOf(current);
int size = visited.size();
int sizeOfLoop = size - currentIndex;
return sizeOfLoop;