class Solution{
public:
ListNode*get(ListNode *headA,ListNode *headB){
ListNode* curA=headA;
ListNode* curA=headB;
int lenA=0,lenB=0;
while(curA!=Null){
lenA++;
curA=curA->next;
}
while(curB!=Null){
lenB++;
curB=curB->next;
}
curA=headA;
curB=head;
if(lenB>lenA){
swap(lenA,lenB);
swap(curA,curB);
}
int gap=lenA-lenB;
while(gap--){
curA=curA->next;
}
while(curA!=NULL){
if(curA==curB){
return curA;
}
curA=curA->next;
curB=curB->next;
}
return NULL;
}
}
一个环,环有什么特点?一个圆圈,圆圈相当于死循环。一个环就是一个结构,是静态得规则。
怎么看到静态规则下其他事物所产生的一些规律。
指针,是个动态的事物,它有方向,有速度,变量等。
怎么才能知道静态规则下事物哪些变量会出现一些规律了?
控制变量,对比实验。两个指针,保持方向一致,速度不一样。或者保持方向相反,速度一致。
保持方向一致,速度不一致下。在这个环中,两个指针定会相遇,相遇意思是相等,相等代表t*v1
t*v1*2=t*v2 s1=s2.它两在环内相遇,共同走过的路程为s3. s2-s3=s1-s3.
class Solution{
public:
ListNode *detectCycle(ListNode *head){
ListNode* fast=head;
ListNode* slow=head;
while(fast !=NULL&&fast->next !=NULL){
slow=slow-next;
fast=fast->next->next;
if (slow==fast){
ListNode* index1=fast;
ListNode* index2=head;
while(index1 !=index2){
index1=index1->next;
index2=index2->next;
}
return index2;
}
}
return NULL;
}
}