inked-list-cycle-ii

题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?

思路

https://www.nowcoder.com/questionTerminal/6e630519bf86480296d0f1c868d425ad

代码

/**
 * 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){
            return null;
        }
        //寻找相遇节点
        ListNode meetNode = findMeetingNode(head);
        if(meetNode==null){
            return null; //无环
        }
        ListNode p1 = head;
        ListNode p2 = meetNode;
        while (p1!=p2){
            p1 = p1.next;
            p2 = p2.next;
        }

        return p1;
    }
    private ListNode findMeetingNode(ListNode head){
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(slow == fast){
                return slow;
            }
        }
        return null;
    }
}