方法一:哈希表
思路:遍历单链表,每次遍历到一个节点时,判断该节点是否在集合中,若节点不在集合中则加入,若在集合中,则说明存在环,返回true;
- 时间复杂度O(N),最坏情况下我们需要遍历每个节点一次。
- 空间复杂度O(N),主要为哈希表的开销,最坏情况下我们需要将每个节点插入到哈希表中一次。
-
/** * 方案一:遍历链表,若节点不在集合中则加入,相反若在集合中,则说明存在环,返回true * @param head * @return */ public static boolean hasCycle(ListNode head) { HashSet<ListNode> set = new HashSet<>(); while(!set.contains(head)){ /*空指针异常*/ /*if(head.next == null){ return false; }*/ if(head == null){ return false; } set.add(head); head = head.next; } return true; }
方法二:快慢指针
-
思路:A和B两个人以不同的速度沿着单链表走步 ,若两人能相遇,则说明存在环
我们定义两个指针,一快一满。慢指针每次只移动一步,而快指针每次移动两步。初始时,慢指针在位置 head,而快指针在位置 head.next。这样一来,如果在移动的过程中,快指针反过来追上慢指针,就说明该链表为环形链表。否则快指针将到达链表尾部,该链表不为环形链表。
-
时间复杂度:O(N),当链表中不存在环时,快指针将先于慢指针到达链表尾部,链表中每个节点至多被访问两次。
当链表中存在环时,每一轮移动后,快慢指针的距离将减小一。而初始距离为环的长度,因此至多移动 NN 轮。
空间复杂度:O(1)。我们只使用了两个指针的额外空间。
-
/** * 方案二:A和B两个人以不同的速度沿着单链表走步 ,若两人能相遇,则说明存在环 * @param head * @return */ public static boolean hasCycleTwo(ListNode head) { ListNode first = head; ListNode two = head; /** * 如果A能走到头则说明,不存在环 */ if (first != null) { first = first.next; }else{ return false; } /** * 若B能走到头则说明不存在环 */ if (two != null) { two = two.next; if (two != null) { two = two.next; }else { return false; } }else{ return false; } /** * 若A和B能相遇则说明,存在环 */ while(first != two) { if (first != null) { first = first.next; }else{ return false; } if (two != null) { two = two.next; }else{ return false; } if (two != null) { two = two.next; }else { return false; } } return true; }
public boolean hasCycleTwos(ListNode head) {
if (head == null || head.next == null) {
return false;
}
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;
}