Answers and Comments


User Avatar
Written by CMaster


If there are no requirements on using extra memory and keeping the list in its original state very neat and simple approach can be uses. The idea is based on the fact that if you reverse the list which has loops you will end-up on the head node while if list doesn’t have loops you will stop at the tail:

public bool hasLoop(Node head)
{

Node first=null;
Node second=null;
Node tmp=head;

while(tmp)
{
first=second;
second=tmp;
tmp=tmp.Next;
if(tmp==head) return true;
second.Next=first;
}

return false;
}


User Avatar
Written by elenashutova


bool IsCircular(LList* pHead)
{
bool bCIrc = false;
LList* p1 = pHead;
LList* p2 = pHead;

while (pr1)
{
p1 = p1->next;
p2 = p2->next;

if (p2)
p2=p2->next;

if (p1 == p2)
{
bCirc = true;
break;
}
}
return bCirc;
}

There is additional question to the original problem:
To find a joint pont.


Saved Stories

Sponsored Categories