1.Question
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;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head || !head->next) return false;
ListNode *one_stride = head, *two_stride = head->next;
while(two_stride->next && two_stride->next->next)
{
if(one_stride == two_stride) return true;
else
{
one_stride = one_stride->next;
two_stride = two_stride->next->next;
}
}
return false;
}
};
3.Note
a. 这里利用的trick是让前进快和前进慢的指针同时前进,如果有环的话,则他们两个会相遇。