/**
* 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 = new ListNode;
ListNode *slow = new ListNode;
fast=head;
slow=head;
while(fast&&slow){
if(fast->next==NULL){
return false;
}
else if(fast->next->next==NULL){
return false;
}
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
return true;
}
}
return false;
}
};
思想:快慢指针,fast一次走2,slow一次走1,如果能重合就是有环。
法2:哈希map
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_map <ListNode *,int> m;
while(head)
{
m[head]++;
if(m[head] > 1) return true;
head = head->next;
}
return false;
}
};