1.题目:​​https://leetcode-cn.com/problems/linked-list-cycle/​

2.思路:

(1)双指针(快慢指针)来判断是否是环路
(2)哈希思想:设成一个不会出现的特殊值就行了,重点是在原数据结构上标记的思想

3.代码:

参考:https://leetcode-cn.com/problems/linked-list-cycle/solution/kuai-man-zhi-zhen-da-jia-jian-de-duo-liao-lai-ge-z/
https://leetcode-cn.com/problems/linked-list-cycle/comments/97300
方法1
/**
* 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 false;
ListNode *fast= head;
ListNode *slow= head;
while (fast!=NULL && fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if (fast==slow)
return true;
}
return false;

}
};
方法2:
/**
* 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 false;
ListNode *fast=head;
while (fast!=NULL && fast->val!=99999999)
{
fast->val=99999999;
fast=fast->next;
}
if (fast!=NULL)
return true;
else
return false;

}
};