typedef struct listNode {
int val;
struct listNode *next;
} listNode;
struct ListNode *detectCycle(struct ListNode *head) {
if (head == NULL || head->next == NULL || head->next->next == NULL) return NULL;
struct listNode *fast = head, *slow = head, *ret;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (fast == slow) break;
}
if (fast->next == NULL || fast->next->next == NULL) return NULL;
ret = head;
while (slow != ret) {
ret = ret->next;
slow = slow->next;
}
return ret;
}
暂无评论