思路:
双指针法。1.先判断是否有环:快指针每次比慢指针多走两步,若有环则必会相遇。2.推导得:头结点到环起点的距离=相遇点到环起点的距离
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//双指针法。1.先判断是否有环:快指针每次比慢指针多走两步,若有环则必会相遇。2.推导得:头结点到环起点的距离=相遇点到环起点的距离
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != nullptr && fast->next != nullptr)//以fast作为循环条件,不能用slow
{
fast = fast->next->next;//快指针每次走两步
slow = slow->next;//慢指针每次走一步
if(slow == fast)//若快指针=慢指针,则有环
{
ListNode* cur = head;
while(cur != slow)//头结点到环起点的距离=相遇点到环起点的距离
{
cur = cur->next;
slow = slow->next;
}
return cur;
}
}
return NULL;
}
};