判断单向链表中有没有形成环,如果形成环,请找出环的入口处,即P点

2020-04-17T23:39:45
/*
 *单链表的结点类
 */
class LNode{
    //为了简化访问单链表,结点中的数据项的访问权限都设为public
    public int data;
    public LNode next;
}


class LinkListUtli {
    //当单链表中没有环时返回null,有环时返回环的入口结点
    public static LNode searchEntranceNode(LNode L)
    {
        LNode slow=L;//p表示从头结点开始每次往后走一步的指针
        LNode fast=L;//q表示从头结点开始每次往后走两步的指针
        while(fast !=null && fast.next !=null) 
        {
            if(slow==fast) break;//p与q相等,单链表有环
            slow=slow.next;
            fast=fast.next.next;
        }
        if(fast==null || fast.next==null) return null;

        // 重新遍历,寻找环的入口点
        slow=L;
        while(slow!=fast)
        {
            slow=slow.next;
            fast=fast.next;
        }

        return slow;
    }
}
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »