第一反应是遍历链表,将历史节点存放在map中(hash),遍历过程发现历史数据包含当前节点,则判断为有环: 1、历史节点法:

package main
import . "nc_tools"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
*/
func hasCycle( head *ListNode ) bool {
    // write code here
    contains := make(map[interface{}]int, 0)
    for head != nil{
        v, _ := contains[head]//判断是否已经存在当前节点
        if v == 1 {
            return true
        }
        contains[head] = 1//存入当前节点
        head = head.Next //循环下一个节点
    }
    return false
    
}

2、快慢指针

package main
import . "nc_tools"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 
 * @param head ListNode类 
 * @return bool布尔型
*/
func hasCycle( head *ListNode ) bool {
    // write code here
    //快慢指针
    fast, slow := head, head
    
    for fast != nil && fast.Next != nil{
        fast = fast.Next.Next
         slow = slow.Next
        if fast == slow{
             return true
        }
     }
    return false
}