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;
}
}
}
}
来源:CSDN
作者:javalj_hz
链接:https://blog.csdn.net/l4oli/article/details/104049757