解法一:哈希表

思路同141. 环形链表解法一。

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public ListNode detectCycle(ListNode head) {
  14. Set<ListNode> set = new HashSet<>();
  15. while (head != null) {
  16. if (set.contains(head)) {
  17. return head;
  18. }
  19. set.add(head);
  20. head = head.next;
  21. }
  22. return null;
  23. }
  24. }

解法二:快慢指针

思路同141. 环形链表解法二,但是判断有环后找出环的起始结点还需要进一步处理。通过简单数学计算可以发现从链表头出发,和慢指针以相同的步长移动会在环的起始结点相遇。

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public ListNode detectCycle(ListNode head) {
  14. ListNode p1 = head;
  15. ListNode p2 = head;
  16. while ((p1 != null) && (p2 != null)) {
  17. p1 = p1.next;
  18. if (p1 != null) {
  19. p1 = p1.next;
  20. } else {
  21. break;
  22. }
  23. p2 = p2.next;
  24. if (p1 == p2) {
  25. ListNode ans = head;
  26. while (ans != p2) {
  27. ans = ans.next;
  28. p2 = p2.next;
  29. }
  30. return ans;
  31. }
  32. }
  33. return null;
  34. }
  35. }