給定一個鏈表,判斷鏈表中是否有環。
進階: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