剑指Offer-链表-面试题23:链表中环的入口节点

CONTENT


给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值