33 lines
488 B
Go
33 lines
488 B
Go
// Package q142 implements a solution for https://leetcode.com/problems/linked-list-cycle-ii/
|
|
package q142
|
|
|
|
type ListNode struct {
|
|
Val int
|
|
Next *ListNode
|
|
}
|
|
|
|
func detectCycle(head *ListNode) *ListNode {
|
|
p1, p2 := head, head
|
|
for p1 != nil && p2 != nil {
|
|
p1 = p1.Next
|
|
p2 = p2.Next
|
|
if p2 != nil {
|
|
p2 = p2.Next
|
|
}
|
|
if p1 == p2 {
|
|
break
|
|
}
|
|
}
|
|
if p2 == nil {
|
|
return nil
|
|
}
|
|
|
|
p1 = head
|
|
for p1 != p2 {
|
|
p1 = p1.Next
|
|
p2 = p2.Next.Next
|
|
}
|
|
return p1
|
|
}
|
|
|
|
var _ = detectCycle
|