在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
}