142环形链表

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值