LeetCode—面试题:环路检测(快慢指针)

环路检测(中等)

2020年10月14日

题目来源:力扣

在这里插入图片描述

解题
链表判断有环容易想到用快慢指针,但这道题需要判断环的入口

首先用快慢指针判断是否有环,如果有环,那么把慢指针指向头节点,与快指针同时移动,找第一个相同的节点,那就是环入口节点
数学推导如下:来自题解
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    
    public ListNode detectCycle(ListNode head) {
    
    
        //两个以上才能成环
        if(head==null || head.next==null) return null;
        //初始化快慢指针
        ListNode fast=head;
        ListNode slow=head;
        //如果快指针不为空且快指针的下个节点不为空可继续循环
        while(fast!=null && fast.next!=null){
    
    
            fast=fast.next.next;
            slow=slow.next;
            //如果相遇,有可能是为空,也有可能不为空
            if(fast==slow)
                break;
        }
        //如果相遇点为空或相遇点下个为空就退出,无环
        if(fast==null || fast.next==null){
    
    
            return null;
        }
        //让慢指针回到头节点
        slow=head;
        //从头节点走到环开始节点和从相遇点走到环开始节点的长度相同
        while(slow!=fast){
    
    
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/109075767
今日推荐