142. 环形链表 II

image.png
image.png

题解

141. 环形链表 不同的点在于本题要求返回环的入口,寻找环的入口是本题难点。

快慢指针

image.png

  1. public class Solution {
  2. public ListNode detectCycle(ListNode head) {
  3. if (head == null || head.next == null) return null;
  4. ListNode slow = head;
  5. ListNode fast = head;
  6. while (fast != null && fast.next != null) {
  7. fast = fast.next.next;
  8. slow = slow.next;
  9. // 说明有环
  10. if (fast == slow) {
  11. ListNode tmp = head;
  12. // 找到环的第一个
  13. while (tmp != slow) {
  14. tmp = tmp.next;
  15. slow = slow.next;
  16. }
  17. return tmp;
  18. }
  19. }
  20. return null;
  21. }
  22. }

哈希表

image.png

  1. public class Solution {
  2. public ListNode detectCycle(ListNode head) {
  3. if (head == null || head.next == null) return null;
  4. Set<ListNode> set = new HashSet<>();
  5. while (head != null) {
  6. if (set.contains(head)) {
  7. return head;
  8. } else {
  9. set.add(head);
  10. }
  11. head = head.next;
  12. }
  13. return null;
  14. }
  15. }