大致题意:如果单链表有环,找出环的入口节点(环的连接点)
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
public class ListNode(int x) {
int data;
ListNode next;
public ListNode(int data) {
this.data = data;
this.next = null;
}
}
public ListNode getNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(slow!= null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) break;
}
if(fast == null || fast.next == null) return null;
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}