[LeetCode]Link List Cycle II
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?
思考:第一步:设环长为len,快慢指针q、p相遇时,q比p多走了k*len。
第二部:p先走k*len步,p,q一起走每次一步,相遇时p比q多走了一个环距离,此时q就是环开始结点。
通过分析AC的感觉真好!
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(!head||!head->next) return NULL;
ListNode *p=head;int countP=0;
ListNode *q=p->next;int countQ=1;
bool flag=false;
int len=0;
while(q&&q->next)
{
if(p==q)
{
len=countQ-countP;
flag=true;
break;
}
else
{
q=q->next->next;
p=p->next;
countP+=1;
countQ+=2;
}
}
if(flag)
{
p=head;
q=head;
while(len--)
{
p=p->next;
}
while(p!=q)
{
p=p->next;
q=q->next;
}
return p;
}
else return NULL;
}
};

浙公网安备 33010602011771号