万事开头难
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
typedef struct ListNode* ListNode;
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;
}
}
return NULL;
}