Description:一个链表中包含环,请找出该链表的环的入口结点。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode head)
{
//先找碰撞点
ListNode slow = head;
ListNode fast = head;
while (fast != 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;
}
}