目录
题目叙述
题解代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//设置快慢指针
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && fast->next != NULL){
//慢指针一次走一步,快指针一次走两步
slow = slow->next;
fast = fast->next->next;
//直到快慢指针相遇
if(slow == fast)
{
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1 != index2)
{
index1 = index1->next;
index2 = index2->next;
}
return index2;
}
}
return NULL;
}
};
提交结果