Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
这道题非常常见,http://blog.csdn.net/hf81970/article/details/14169655 这篇文章讲的非常全面。分析简单明确。
代码:
/**
* 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* fast = head->next->next, * slow = head->next;
ListNode* start = NULL;
while(fast && slow)
{
if(fast == slow)
{
start = fast;
break;
}
slow = slow->next;
fast = fast->next;
if(!fast)
return NULL;
fast = fast->next;
}
if(start == NULL)
return NULL;
ListNode * p1 = start, *p2 = head;
while(p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};