/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ import java.util.ArrayList; public class Solution { public ListNode EntryNodeOfLoop(ListNode pHead) { ArrayList<ListNode> list = new ArrayList<>(); ListNode node = pHead; while(node != null){ if(list.contains(node)){ return node; }else{ list.add(node); node = node.next; } } return null; } }
另一种不需要空间复杂度为O(1)的
if(pHead == null || pHead.next == null || pHead.next.next == null){ return null; } ListNode slow = pHead.next; ListNode fast = pHead.next.next; while(fast != slow){ if(fast.next == null || fast.next.next == null){ return null; } fast = fast.next.next; slow = slow.next; } //得到环的长度 ListNode mid = pHead; fast = fast.next; while(fast != slow){ fast = fast.next; mid = mid.next; } mid = mid.next; fast = pHead; while(fast != mid){ fast = fast.next; mid = mid.next; } return fast;