在Go中遍歷環形鏈表可以通過兩種方法實現:
type ListNode struct {
Val int
Next *ListNode
}
func hasCycle(head *ListNode) bool {
if head == nil || head.Next == nil {
return false
}
slow := head
fast := head.Next
for fast != nil && fast.Next != nil {
if slow == fast {
return true
}
slow = slow.Next
fast = fast.Next.Next
}
return false
}
type ListNode struct {
Val int
Next *ListNode
}
func hasCycle(head *ListNode) bool {
cur := head
for cur != nil {
if cur.Val == -1 {
return true
}
cur.Val = -1
cur = cur.Next
}
return false
}