NC_3_ENTRY_LOOP

package org.example.interview.practice;

/**
 * @author xianzhe.ma
 * @date 2022/1/11
 */

public class NC_3_ENTRY_LOOP {
    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if(pHead == null || pHead.next == null){
            return null;
        }

        ListNode fast = pHead;
        ListNode slow = pHead;

        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                ListNode slow2 = pHead;
                while(slow2 != slow){
                    slow2 = slow2.next;
                    slow = slow.next;
                }
                return slow2;
            }
        }
        return null;

    }

    public static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }
}

 

posted on 2022-02-10 15:34  MaXianZhe  阅读(23)  评论(0编辑  收藏  举报

导航