Espada se refiere a la oferta 23. El nodo de entrada del anillo en la lista vinculada
Descripción del Título
Ideas para resolver problemas
Preste atención al siguiente juicio incorrecto si hay una redacción de anillo:
while (fast != null && fast.next != null && fast != slow) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != slow) return null;
Nota: Cuando solo hay un nodo en la lista vinculada y no forma un anillo , esta escritura será incorrecta. Entonces, al juzgar si hay un anillo, puede cambiarlo aif (fast != null && fast.next != null) return null;
Pero podemos establecer un bit de bandera para que sea más claro.
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;
}
}