Question:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
Answer:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL || head -> next == NULL) return NULL;
ListNode *first = head;
ListNode *second = head;
while (second && second -> next != NULL)
{
first = first -> next;
second = second -> next -> next;
if (first == second)
{
break;
}
}
if (first != second) { return NULL; }
first = head;
while (first != second)
{
first = first -> next;
second = second -> next;
}
return first;
}
};
算法分析参考:http://www.cnblogs.com/hiddenfox/p/3408931.html