Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
注意:此处循环链表不是指结尾指向开头,结尾可能指向任何一处。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *p,*q;
p=head;
q=head;
while(p!=NULL&&q!=NULL&&q->next!=NULL)
{
p=p->next;
q=q->next->next;
if(p==q)
return true;
}
return false;
}