题目:判断链表是否有环

//环形链表


//哈希表
func hasCycle(head *ListNode) bool {
    seen := map[*ListNode]struct{}{}
    for head != nil {
        if _, ok := seen[head]; ok {
            return true
        }

        //标记该节点已被访问
        seen[head] = struct{}{}
        head = head.Next
    }

    return false
}

//快慢指针
func hasCycle(head *ListNode) bool {
    if head == nil || head.Next == nil {
        return false
    }

    slow, fast := head, head.Next
    for fast != slow {
        if fast == nil || fast.Next == nil {
            return false
        }
        //慢指针一次移动2步
        slow = slow.Next
        //快指针一次移动2步
        fast = fast.Next.Next
    }

    return true
}

链接:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/