在Go中遍歷環(huán)形鏈表可以通過(guò)兩種方法實(shí)現(xiàn):
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
}