head ,返回链表开始入环的第一个节点。 如果链表无环,则返回
null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。

提示:
进阶:你是否可以使用 O(1) 空间解决此题?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> kkset;
while(head){
if(kkset.count(head))
// 返回值有变化
return head;
kkset.insert(head);
head = head->next;
}
return NULL;
}
};

class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast, *slow;
fast = slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
// 环前长度a 相遇距环点b 差c走完一环
// 2*(a+b) = a + n(b+c) +b
// a = (n−1)b+nc = (n−1)(b+c)+c
// slow差c步到入环点
// a + a + b = (2n-1)(b+c) + c
// 所以slow跟着head走a步一定会到入环点
while(head != slow){
head = head->next;
slow = slow->next;
}
return head;
}
}
return NULL;
}
};
