LC.P142[环形链表II] 方法一:哈希表12345678910111213141516171819202122/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { Set<ListNode> set = new HashSet<>(); ListNode p = head; while (p != null) { if (!set.add(p)) return p; p = p.next; } return null; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$ 方法二:快慢指针123456789101112131415161718192021222324252627282930/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { ListNode fast = head, slow = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; // 存在环 if (slow == fast) { ListNode ans = head; while (ans != slow) { ans = ans.next; slow = slow.next; } return ans; } } return null; }} 时间复杂度:$O(n)$ 空间复杂度:$O(1)$