题目
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?
原题:
https://leetcode.com/problems/linked-list-cycle-ii/
解答
/**
* 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) return NULL;
ListNode *next1=head,*next2=head,*begin=head;
bool Existcycle=false;
while(next2!=NULL&&next2->next!=NULL)//这个判断条件很重要!!!易错!
{
next1=next1->next;
next2=next2->next->next;
if(next1==next2)
{
Existcycle=true;
break;
}
}
if(Existcycle)
{
while(begin!=next1)
{
begin=begin->next;
next1=next1->next;
}
return begin;
}
else
return NULL;
}
};
总结:使用快慢双指针来判断是否存在环,记录相遇位置p,然后再用速度一样的指针,分别从p和head开始,遍历,再次相遇,就是环开始的地方。