mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-28 22:51:54 +08:00
规范格式
This commit is contained in:
@ -0,0 +1,44 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"github.com/halfrost/LeetCode-Go/structures"
|
||||
)
|
||||
|
||||
// ListNode define
|
||||
type ListNode = structures.ListNode
|
||||
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
func detectCycle(head *ListNode) *ListNode {
|
||||
if head == nil || head.Next == nil {
|
||||
return nil
|
||||
}
|
||||
isCycle, slow := hasCycle142(head)
|
||||
if !isCycle {
|
||||
return nil
|
||||
}
|
||||
fast := head
|
||||
for fast != slow {
|
||||
fast = fast.Next
|
||||
slow = slow.Next
|
||||
}
|
||||
return fast
|
||||
}
|
||||
|
||||
func hasCycle142(head *ListNode) (bool, *ListNode) {
|
||||
fast := head
|
||||
slow := head
|
||||
for slow != nil && fast != nil && fast.Next != nil {
|
||||
fast = fast.Next.Next
|
||||
slow = slow.Next
|
||||
if fast == slow {
|
||||
return true, slow
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
Reference in New Issue
Block a user