环形链表的解法:
- 哈希表记录,如果存在相同的说明有环
- 快慢指针解法,如果有环那么慢指针和快指针一定会相交
public class Solution {public boolean hasCycle(ListNode head) {if(head == null || head.next == null) return false;//1. 快慢指针解法 判断环形链表// ListNode slow = head;// ListNode fast = head.next;// while(slow != fast){// if(fast == null || fast.next == null) return false;// slow = slow.next;// fast = fast.next.next;// }// //如果两个相交则说明有环// return true;//2. 通过哈希表的方式遍历链表,如果遇见相同的则表示有环HashSet<ListNode> set = new HashSet<>();while(head != null){if (set.contains(head)) {//说明有环return true;}set.add(head);head = head.next;}return false;}}
如何判断链表的环长和入环的节点:
从p1 和 p2 首次相遇开始计算,下一次相遇就是环长; 当p1和p2相遇,将p1移动到链表的头部,p1和p2每次步长为1,当p1和p2相遇则为入环的节点;
