Sword refers to offer 23. The entry node of the ring in the linked list
Title description
Problem-solving ideas
Pay attention to the following wrong judgment whether there is a ring wording:
while (fast != null && fast.next != null && fast != slow) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != slow) return null;
Note: When there is only one node in the linked list , and it does not form a ring , this way of writing will be wrong. So when judging whether there is a ring, you can change it toif (fast != null && fast.next != null) return null;
But we can set a flag bit to make it clearer.
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;
}
}