Description:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:
双指针法遍历单链表,一个快指针,一个慢指针,快指针走两步,慢指针走一步,如果存在环,则快指针必定与慢指针相遇。如果快慢指针相遇,也同时说明存在环。
Solution:
/**
* 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 == NULL) return NULL;
ListNode* S = head;
ListNode* F = head;
while(F != NULL){
if(F) F = F -> next;
if(F) F = F -> next;
if(S) S = S -> next;
if(F != NULL && F == S){
return true;
}
}
return false;
}
};