给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路
(1)首先需要解决的是如何判断一个链表中有环。快慢双指针的运用,类比于速度为1和2。
(2)计算出环的长度。一圈下来即为长度。
(3)找到环的入口结点。双指针的运用,一个指针先出发,然后以相同的速度运动。为什么他们相遇的点就是环的起始点呢?假设链表总长度是k(k=m+n),环的长度为n,那么,指针1先走n,然后两个指针同时同速出发,到他们相遇时,就是指针1走完了剩下的m=k-n,而指针2走的路程与指针1相同也是m,后面还剩下的路程为k-m=n,恰好剩下一个环的长度,因此这个点就是环的入口。
(4)错误的输入,以及没找到环的情况下,都需要拦截,return null;
。
(5)需要习惯不使用IDE环境下写代码,以及通过测试用例找bug;后期训练更需要连测试用例的提示都没有。
【1】当我们使用一个指针遍历链表不能解决问题时,可以用两个指针,并且有不同速度,先后顺序不同的情况运用。
解法
nowcoder的AC
提交时间:2020-01-02 ,语言:Java ,运行时间: 20 ms, 占用内存:9704K ,状态:答案正确
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead){
//1.judge there is a circle
//2.caculate the length of the circle
//3.find the entrance of the circle
if(pHead.next==null || pHead.next.next==null){
return null;
}
ListNode node1=pHead.next;
ListNode node2=pHead.next.next;
while(node1!=node2 && node1!=null){
node1=node1.next;
node2=node2.next.next;
}
//if don't find circle
if(node1==null || node2==null){
return null;
}
//step in here,there must have a circle;
int len=0;
do{
node1=node1.next;
node2=node2.next.next;
len++;
}while(node1!=node2);
//step3,find the first point of this circle
node1=pHead;
node2=pHead;
for(int i=0;i<len;i++){
node1=node1.next;
}
while(node1!=node2){
node1=node1.next;
node2=node2.next;
}
return node1;
}
}