问题描述:
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
public static ListNode EntryNodeOfLoop(ListNode head){
if (head == null){ // 如果头指针为空,肯定没有链表,跟没有环啊
return null;
}
ListNode fast = head; // 设置快指针
ListNode slow = head; // 设置慢指针
int flag = 0; // 设置是否有环的标志位
// fast指针用slow指针二倍的速度向后移动,
while (fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
if (fast == slow){ // 相等的时候表明链表中有环
flag = 1;
break;
}
}
if (flag == 0){ // 没有环
return null;
} else {
// 有环的时候,slow指针和新指向头指针的指针同步向后移动,相遇的时候指向的节点为入口节点
ListNode newHead = head;
while (newHead != slow){
newHead = newHead.next;
slow = slow.next;
}
}
return slow;