剑指offer 23.链表中环的入口节点
题目描述
解题思路
注意下面这种错误的判断是否有环的写法:
while (fast != null && fast.next != null && fast != slow) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != slow) return null;
说明:当链表中仅有一个节点,且不构成环时,这种写法会出错。所以判断是否有环时,可以改成 if (fast != null && fast.next != null) return null;
但我们可以设置一个标志位,更清楚一些。
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if(pHead == null) return null;
ListNode fast = pHead, slow = pHead; //快慢指针
boolean hasCycle = false; //标志是否有环
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
hasCycle = true;
break;
}
}
//没有环则直接返回null
if (!hasCycle) return null;
//如果有环,则令fast从头开始,并和slow同步移动,直到相遇,则为环的入口节点
fast = pHead;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return fast;
}
}