Sunday, April 1, 2012

How to check if a link list is circular of is a loop??

This is one of the important question interviewers askes and you are supposed to at least give a logical answer to it, so the logic behind this is to “ Create two markers (pointers) move one pointer faster other slower in a loop, so if these two pointers meets at some point, before the link list ends (while not null) means the link list is circular else if the two pointer meets when the link list ends means while null becomes true means the link list is not circular.

 

Example Code :

 

while (SlowPointer) {
SlowPointer = SlowPointer->next;
FastPointer = FastPointer->next;
if (FastPointer) FastPointer=FastPointer->next;
if (SlowPointer == FastPointer) {
print ("circular\n");
}
}

No comments:

Post a Comment

Live

Your Ad Here