您好,欢迎来到汇智旅游网。
搜索
您的当前位置:首页剑指offer 34. 链表中环的入口结点-java实现

剑指offer 34. 链表中环的入口结点-java实现

来源:汇智旅游网

AcWing 34. 链表中环的入口结点

这道题非常经典 是采用快慢指针进行计算 相当于小学的追及问题
用数学方式可以证明 也包括求出环的个数 环入口 环内有几个结点

给定一个链表,若其中包含环,则输出环的入口节点。

若其中不包含环,则输出null。

数据范围
节点 val 值取值范围 [1,1000]。
链表长度 [0,500]。

题解

用两个指针 first,second 分别从起点开始走,first 每次走一步,second 每次走两步。 图中的因为速度差是二倍 第一次相遇走的路程也是它的二倍
求出 a+b = k*s k 是走过的环的次数 s是环的周长
如果过程中 second 走到null,则说明不存在环
否则当 first 和 second 相遇后,让 first 返回起点,second 待在原地不动,等到first从起点出发 一起走 然后两个指针每次分别走一步, 这时候二者速度一样
当相遇时,相遇点就是环的入口。也就是a相当于环中减掉b的那部分 相遇点就是环的入口处

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
class Solution {
    public ListNode entryNodeOfLoop(ListNode head) {//判断环的入口 定义快慢指针
        if(head==null || head.next==null){//空结点判定
            return null;
        }
        ListNode fast=head;
        ListNode slow=head;
        int ringLength=1;
        while(fast.next!=null && fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow){//二者相遇
                slow=slow.next;
                while(fast!=slow){
                    slow=slow.next;
                    ringLength++;
                }
                fast=slow=head;
                for(int i=0;i<ringLength;i++){
                    fast=fast.next;
                }
                while(fast!=slow){
                    fast=fast.next;
                    slow=slow.next;
                }
                return fast;
            }
        }
        return null;
    }
}

两种习惯写法

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
class Solution {
    public ListNode entryNodeOfLoop(ListNode head) {
          if(head==null || head.next==null){//空结点判定
            return null;
        }
        ListNode first=head;
        ListNode second=head;
         while (first != null && second != null)
        {
            first = first.next;
            second = second.next;
            if (second != null) second = second.next;
            if (first == second)
            {
                first = head;
                while (first != second)
                {
                    first = first.next;
                    second = second.next;
                }
                return first;
            }
        }

         return null ;
 
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- hzar.cn 版权所有 赣ICP备2024042791号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务