LeetCode 题解之Linked List Cycle II

时间:2023-03-09 21:27:54
LeetCode 题解之Linked List Cycle II

1、题目描述

LeetCode 题解之Linked List Cycle II

2、问题分析

使用快慢指针方法判断链表是否有环,然后寻找环开始的节点。

3、代码

 ListNode *detectCycle(ListNode *head) {
if( head == NULL || head->next == NULL ){
return NULL ;
} ListNode* fast = head;
ListNode* slow = head; while( fast != NULL && slow != NULL ){ if( fast->next != NULL ){
fast = fast->next->next;
}else{
return NULL ;
}
slow = slow->next;
if( fast == slow ){
break;
}
} if( fast == NULL || slow == NULL ){
return NULL;
} ListNode* start = head;
while( start != slow ){
start = start->next ;
slow = slow->next;
} return start; }