链表——环形链表
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL)
{
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 index1;
}
// 不能将index1在此处返回,因为index1在if代码块执行结束之后,会被自动释放
}
return NULL;
}
};

浙公网安备 33010602011771号