Find length of Loop | JAVA | Linked List

preview_player
Показать описание
Placement Preparation

Code is given in the comment section.

Prerequisite:
Рекомендации по теме
Комментарии
Автор

Code:


class Loop
{
int countNodesinLoop(Node head)
{
Node p=head;
HashSet<Node> a=new HashSet<Node>();
int temp=0;
while(p!=null)
{
if(a.contains(p))
{
break;
}
else
{
a.add(p);
p=p.next;
temp=temp+1;
}
}
Node q=head;
int gemp=0;
while(q!=p)
{
gemp++;
q=q.next;
}
return temp-gemp;
}
}

KnowledgeAmplifier