142. 环形链表 II

package leetcode;

public class demo_142 {
    public ListNode detectCycle(ListNode head) {
        //快慢指针,快指针一次走两个节点
        ListNode fast=head;
        ListNode slow=head;
        //判断当前链表是否存在一个环
        while(fast!=null) {
            if(fast.next!=null) {
                fast=fast.next.next;
            }
            else {
                return null;
            }
            slow =slow.next;
            //存在环
            if(slow==fast) {
                break;
            }
        }
        //不存在环
        if(fast==null) {return null;}
        //若存在一个环,则pre和slow总会在换入口时相遇
        ListNode pre=head;
        while(pre!=slow) {
            pre=pre.next;
            slow=slow.next;
        }
        
        return pre;
    }
}

 

posted on 2022-04-12 10:40  一仟零一夜丶  阅读(60)  评论(0)    收藏  举报