环形链表的解法:

    1. 哈希表记录,如果存在相同的说明有环
    2. 快慢指针解法,如果有环那么慢指针和快指针一定会相交
    1. public class Solution {
    2. public boolean hasCycle(ListNode head) {
    3. if(head == null || head.next == null) return false;
    4. //1. 快慢指针解法 判断环形链表
    5. // ListNode slow = head;
    6. // ListNode fast = head.next;
    7. // while(slow != fast){
    8. // if(fast == null || fast.next == null) return false;
    9. // slow = slow.next;
    10. // fast = fast.next.next;
    11. // }
    12. // //如果两个相交则说明有环
    13. // return true;
    14. //2. 通过哈希表的方式遍历链表,如果遇见相同的则表示有环
    15. HashSet<ListNode> set = new HashSet<>();
    16. while(head != null){
    17. if (set.contains(head)) {
    18. //说明有环
    19. return true;
    20. }
    21. set.add(head);
    22. head = head.next;
    23. }
    24. return false;
    25. }
    26. }

    如何判断链表的环长和入环的节点:

    从p1 和 p2 首次相遇开始计算,下一次相遇就是环长; 当p1和p2相遇,将p1移动到链表的头部,p1和p2每次步长为1,当p1和p2相遇则为入环的节点;