链表找环的入口

十年热恋 提交于 2020-01-25 20:35:33
package linkedlist;

/**
 * Created by lijie35 on 2020-01-20 10:43 AM .
 */
public class ListEntrance {
    public static void main(String[] args) {
        Node h1 = new Node(0);
        Node h2 = new Node(1);
        Node h3 = new Node(2);
        Node h4 = new Node(3);
        Node h5 = new Node(4);
        h3.next=h5;
        h5.next = h4;
        h4.next = h5;
        System.out.println(findEntrance(h3).val);
    }


    public static Node findEntrance(Node node) {

        if (node == null || node.next == null)
            return new Node(-1);

        Node meetingPoint = mettingPoint(node);

        if (meetingPoint == null)
            return new Node(-1);

        Node startPoint = node;

        while (true) {

            meetingPoint = meetingPoint.next;
            startPoint = startPoint.next;

            if (meetingPoint == startPoint) {
                return startPoint;
            }
        }

    }


    public static final Node mettingPoint(Node node) {
        if (node == null || node.next == null)
            return null;

        Node slow = node;
        Node fast = node;

        while (true) {

            slow = slow.next;
            fast = fast.next.next;

            if (fast == null || fast.next == null) {
                return null;
            }
            if (fast == slow) {
                return fast;
            }
        }
    }

}


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!