Files
leetcode/top-100-liked/25/25_test.go
T
2026-06-13 04:08:10 +10:00

59 lines
960 B
Go

package top100liked
import (
"fmt"
"testing"
)
// https://leetcode.cn/problems/linked-list-cycle/description/?envType=study-plan-v2&envId=top-100-liked
type ListNode struct {
Val int
Next *ListNode
}
// func hasCycle(head *ListNode) bool {
// _map := make(map[*ListNode]bool)
// for head != nil {
// if _map[head] {
// return true
// }
// _map[head] = true
// head = head.Next
// }
// return false
// }
func hasCycle(head *ListNode) bool {
if head == nil || head.Next == nil {
return false
}
slow, fast := head, head.Next
for fast != slow {
if fast == nil || fast.Next == nil {
return false
}
slow = slow.Next
fast = fast.Next.Next
}
return true
}
func TestS24(t *testing.T) {
input := &ListNode{
Val: 3,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 0,
Next: &ListNode{
Val: -4,
Next: nil,
},
},
},
}
input.Next.Next.Next.Next = input.Next
fmt.Println(hasCycle(input))
}