Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution;
Make a slow pointer which step 1 in each iteration and a fast pointer which step 2 in each iteration.
If there is a cycle, slow would meet fast at some point.
Otherwise fast would reach NULL
Code:
/**
* 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 *fast = head;
ListNode *slow = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next-> next;
if(slow == fast) return true;
}
return false;
}
};