Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it
思路 :两个指针,一个每次移动一位,一个每次移动两位,最终如果相遇说明有环
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) return false;
ListNode *left = head;
ListNode *right = head;
while (right){
left = left->next;
if (right->next)
right = right->next->next;
else
return false;
if (right&&left == right)
return true;
}
return false;
}
};