数学法链表判断是否有环
* 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 != nullptr && fast->next != nullptr)
{
fast = fast->next->next;//快指针每次向后走两步
slow = slow->next;//慢指针走一步
if (fast == slow)//快慢指针相遇,有环
return true;
}
return false;
}
};
使用map法
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
map mp; // 定义一个哈希表存储结点指针
while(head){ // 不断遍历结点
if(mp[head]){ //如果这个结点出现过
return true;
}
// 如果没有出现过,那么标记为1,表示出现过了
mp[head]=1;
head=head->next;
}
return false;
}
};



