给定一个链表,判断链表中是否有环。
进阶:git
你可否不使用额外空间解决此题?
// ListNode Definition for singly-linked list. type ListNode struct { Val int Next *ListNode } func hasCycle(head *ListNode) bool { if head != nil { slow := head fast := head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next if slow == fast { return true } } } return false }
leetcode 141. 环形链表github