/** *对于一个给定的链表,返回环的入口节点,如果没有环,返回null * 拓展: * 你能给出不利用额外空间的解法么? * 核心思路:(快慢指针) * 定义一个快指针每次走两步 * 定义一个慢指针每次走一步 * 快慢指针相遇则一定在环内,且方向相反 * 相遇后慢指针从头开始走,快指针继续走每次只走一步,最后快慢指针相遇一定是入口 * 具体计算参考(https://blog.csdn.net/qq_45731021/article/details/112307606?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-7&spm=1001.2101.3001.4242) * * 代码简单,逻辑比较绕 */ public class NC3 { public ListNode detectCycle(ListNode head) { ListNode fast=head; ListNode slow=head; //判断是否有环 while (fast!=null &&fast.next!=null){ fast= fast.next.next; slow= slow.next; if(slow==fast){ break; } } //循环不满足 表示没有环; if(fast==null || fast.next==null){ return null; } slow=head;//慢指针从头开始 while(slow!=fast){ slow=slow.next; fast=fast.next; } return slow; } }
找链表环入口
最新推荐文章于 2022-04-21 22:30:08 发布