29 lines
519 B
Go
29 lines
519 B
Go
|
package main
|
||
|
|
||
|
type ListNode struct {
|
||
|
Val int
|
||
|
Next *ListNode
|
||
|
}
|
||
|
|
||
|
// This solution uses O(1) memory, but
|
||
|
// runtime duration is a bit more
|
||
|
// unpredictable with a maximum complexity
|
||
|
// of O(n^2) I think.
|
||
|
/**
|
||
|
* Definition for singly-linked list.
|
||
|
* type ListNode struct {
|
||
|
* Val int
|
||
|
* Next *ListNode
|
||
|
* }
|
||
|
*/
|
||
|
func hasCycle(head *ListNode) bool {
|
||
|
slow, fast := head, head
|
||
|
for fast != nil && fast.Next != nil {
|
||
|
slow, fast = slow.Next, fast.Next.Next
|
||
|
if slow == fast {
|
||
|
return true
|
||
|
}
|
||
|
}
|
||
|
return false
|
||
|
}
|