1. public boolean hasCycle(ListNode head) {
    2. // 边界条件
    3. if (head == null || head.next == null) {
    4. return false;
    5. }
    6. // 慢指针 龟
    7. ListNode slow = head;
    8. // 快指针 兔
    9. ListNode fast = head.next;
    10. // 龟兔赛跑不相遇则继续跑,直到相遇
    11. while (slow != fast) {
    12. // 退出条件 跑到尽头
    13. if (fast == null || fast.next== null) {
    14. return false;
    15. }
    16. // 龟走一步
    17. slow = slow.next;
    18. // 兔子走两步
    19. fast = fast.next.next;
    20. }
    21. return true;
    22. }
    1. public boolean hasCycle(ListNode head) {
    2. // 慢指针 龟
    3. ListNode slow = head;
    4. // 快指针 兔
    5. ListNode fast = head;
    6. // 跑到尽头才退出
    7. while (fast != null) {
    8. // 走一步
    9. slow = slow.next;
    10. if (fast.next != null) {
    11. // 走两步
    12. fast = fast.next.next;
    13. } else {
    14. // 跑到尽头才退出
    15. return false;
    16. }
    17. // 环路
    18. if (slow == fast) {
    19. return true;
    20. }
    21. }
    22. return false;
    23. }
    1. public boolean hasCycle(ListNode head) {
    2. ListNode slow = head;
    3. ListNode fast = head;
    4. while (fast != null && fast.next != null) {
    5. slow = slow.next;
    6. fast = fast.next.next;
    7. if (slow == fast) {
    8. return true;
    9. }
    10. }
    11. return false;
    12. }
    1. public boolean hasCycle(ListNode head) {
    2. // 边界条件
    3. if (head == null || head.next == null) {
    4. return false;
    5. }
    6. HashSet<ListNode> set = new HashSet<ListNode>();
    7. while (head != null) {
    8. // 检查是否有重复添加
    9. if (!set.add(head)) {
    10. return true;
    11. }
    12. head = head.next;
    13. }
    14. return false;
    15. }