Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
证明方法:http://www.tuicool.com/articles/3EZJbm
//本题的思路是首先采用两个指针分别指向链表的头节点,第一个指针一次向前走一步,第二个指针一次向前走两步,当两个指针第一次相遇时,
//则表明链表存在环,并将当前标记的节点记为节点1,然后同时设置两个指针,指针1和指针2指针1从节点1开始遍历链表,指针2从链表头
//开始遍历链表看,则两个指针相遇时便是链表环的入口
ListNode *detectCycle(ListNode *head) {
if(NULL == head || NULL == head->next)
{
return NULL;
}
else if(head->next == head)
{
return head;
}
ListNode *slow = head;
ListNode *fast = head;
while(fast)
{
fast = fast->next;//注意fast指针是一次向前走两步,但是一次向前走两步,并不能一次直接fast = fast->next->next,
//因为fast->next有可能为空,如果不加以判断会报runtime的错误。
if(fast)
{
fast = fast->next;
slow = slow->next;
}
if(slow == fast)
{
break;
}
}
slow = head;
while(slow && fast)
{
if(slow == fast)
{
return slow;
break;
}
slow = slow->next;
fast = fast->next;
}
return NULL;
}