142. 环形链表 II - 力扣(LeetCode)
struct ListNode *detectCycle(struct ListNode *head)
{
struct ListNode *fast=head;
struct ListNode *slow=head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast==slow)
{
while(slow!=head)
{
slow = slow->next;
head = head->next;
}
return head;
}
}
return NULL;
}
思路:定义快慢指针,先判断是否有环,如果有环就slow和fast相遇,此时,slow开始向后走一步,head向后走一步,当slow和fast相遇时,便是环的第一个节点。