Given a linked list, determine if it has a cycle in it.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head)
{
struct ListNode *p1;
struct ListNode *p2;
p1=head;
p2=head;
if(p1==NULL||p1->next==NULL)
return false;
while(p2->next!=NULL&&p2->next->next!=NULL)
{
p1=p1->next;
p2=p2->next->next;
if(p1==p2)
return true;
}
return false;
}