# Niuke.com High-Frequency Algorithm Question Series-BM6-Determine whether there is a cycle in the linked list

## Niuke.com High-Frequency Algorithm Question Series-BM6-Determine whether there is a cycle in the linked list

#### Topic description

Checks whether there is a cycle in the given linked list. Returns true if there is a loop, false otherwise.

See the original title: BM6 determines whether there is a cycle in the linked list

#### Solution 1: Double pointer method

Use two pointers, fast and slow. They all start at the head of the linked list. Subsequently, the slow pointer moves backward one position at a time, while the fast pointer moves backward two positions. If there is a ring in the linked list, the fast pointer will eventually meet the slow pointer again in the ring.

For the principle, please refer to: Detailed explanation of the principle of double pointer algorithm

#### Solution 2: Hash method

Use HashSet to record the nodes in the linked list, and then traverse the linked list nodes:

• If the node in the linked list has appeared in the hash table, it means that the linked list has a ring, and returns true directly
• If the node in the linked list has not appeared in the hash table, add the current node to the hash table, and then judge the next node

Finally, if there are no duplicate nodes, it means there is no cycle and returns false.

#### code

``` ```import java.util.HashSet;

public class Bm006 {
/**
* 双指针
*
* @return
*/
public static boolean hasCycle(ListNode head) {
while (fast != null && fast.next != null) {
// 快指针每次走2步，慢指针每次走1步
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
// 快慢指针相遇，说明链表中有环
return true;
}
}
// 快慢指针没有相遇，说明无环
return false;
}

/**
* 哈希法
*
* @return
*/
public static boolean hasCycle2(ListNode head) {
// 用来记录链表中未重复的结点
HashSet<ListNode> nodes = new HashSet<>();
// 如果链表中的结点已经出现过，说明有环，返回true
return true;
}
}
// 如果没有重复节点，则说明无环，返回false。
return false;
}

public static void main(String[] args) {
/**
* 测试用例链表结构为有环
* testCaseCycle：  3 -> 2 -> 0 -> -4
*                      ^          |
*                      ------------
*/
/**
* 测试用例，期望输出： true
*/