public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null){
return null;
}
ListNode slow = pHead;
ListNode fast = pHead;
boolean flag = false;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (slow == fast){
flag = true;
break;
}
}
if (!flag){
return null;
}else {
int count = 1;
fast = fast.next;
while(fast != slow){
count++;
fast = fast.next;
}
fast = pHead;
slow = pHead;
for (int i = 0; i < count; i++) {
fast = fast.next;
}
while (fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
}
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead == null || pHead.next == null){
return null;
}
ListNode fast = pHead;
ListNode slow = pHead;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
ListNode slow2 = pHead;
while(slow2 != slow){
slow2 = slow2.next;
slow = slow.next;
}
return slow2;
}
}
return null;
}
}
参考
https://leetcode.com/problems/linked-list-cycle-ii/discuss/44774/Java-O(1)-space-solution-with-detailed-explanation