Given a linked list, determine if it has a cycle in it.
使用两个指针,一前一后,(p,q),p与q相差一个位置,之后p移动一步,q相对应移动两步,如果存在环,那么q和p一定会相遇
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *p,*q;
if(head==NULL)
{
return false;
}
p = head;
q = head->next;
while(q!=NULL && q->next!=NULL)
{
if(p==q)
{
return true;
}
p = p->next;
q = q->next;
q = q->next;
}
return false;
}
};