Samsung Interview Question
Software Engineer InternsTeam: Android
Country: United States
Interview Type: Phone Interview
Use two pointers : slow and fast. Slow pointer moves forward by one step and fast by two steps. If your linked list does not have a cycle then your fast will reach the end of linked list and the check will terminate. If there is a cycle, then fast and slow pointer will collide at some point. So, if fast == slow then there is a cycle in the linkedlist.
steps:
1)Fist create 2 pointer
slow pointr and fast pointer
2) both point to the starting node
Node *slowPtr=Start;
Node *FastPtr=Start;
3)now forward slow pointer by one step and fast pointer by 2 step
while(Start!=NULL)
{
FastPtr=Fast->next->next
SlowPtr=slow->next
if(SlowPtr==FastPtr)
return 1;
}
4 exit
while (cur != NULL) {
if (cur->data == "cycle") {
return true;
}
cur = cur->next;
}
return false;
- chriscow January 29, 2014