Given a linked list, deter if it has cycle in it.
Follow up: can you solve it without using extra space?
Idea: use slow and fast pointer, if there is a cycle, then fast will run in the cycle, and catch the slow pointer.
Running time: O(n), no 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) return false;
if(head->next == NULL) return false;
ListNode
*pSlow = head,
*pFast = head;
while(pFast!=NULL && pFast->next !=NULL)
{
pSlow = pSlow->next;
pFast = pFast->next->next;
if(pSlow == pFast)
{
return true;
}
}
return false;
}
};