链表题
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
一开始不知道思路,后来看快慢指针里给出了大概思路
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* first = head;
ListNode* second = head;
while(second != NULL && second->next != NULL)
{
first = first->next;
second = second->next->next;
if(first == second)
break;
}
if(second != NULL && second->next != NULL)
{
second = head;
while(second != first)
{
second = second->next;
first = first->next;
}
return first;
}
return NULL;
}
};