Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
算法思想:一个指针速度1向后走,一个指针速度2向后走,若相遇则必有环,(有环则必相遇)。
/**
* 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=head,*q=head;
while(q!=NULL&&q->next!=NULL){
p=p->next;
q=q->next->next;
if(p==q)return true;
}
return false;
}
};