考点
快慢指针
思路
- 快指针一次走两步,慢指针一次走一步
- 当快指针和慢指针相遇时,再重定义两个指针index1和index2,index1指向fast,index2指向head
- 当index1与index2相遇时,返回任意一个index即可
代码
class Solution {
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *fast = head;
ListNode *slow = head;
while(fast != nullptr && fast->next != nullptr)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
ListNode *index1 = fast;
ListNode *index2 = head;
while(index1 != index2)
{
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return nullptr;
}
};
// @lc code=endnu