-
Notifications
You must be signed in to change notification settings - Fork 0
/
question22.go
55 lines (43 loc) · 940 Bytes
/
question22.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package chapter04
import "github.com/syhily/code-interviews/common"
// detectCircleInListNode will return a node in circle, else will return nil.
func detectCircleInListNode(l *common.ListNode) *common.ListNode {
// Guard logic, in case of the empty or single list node.
if l == nil || l.Next == nil {
return nil
}
fast, slow := l, l
for fast != nil {
fast = fast.Next
// In case of there is no circle and the fast pointer hit the end.
if fast != nil {
fast = fast.Next
} else {
return nil
}
slow = slow.Next
if slow == fast {
break
}
}
if fast == nil {
// Didn't find the circle
return nil
}
return slow
}
// findStartNodeInCircle will return a start node of a circle in list node.
func findStartNodeInCircle(l *common.ListNode) *common.ListNode {
n := detectCircleInListNode(l)
if n == nil {
return nil
}
s := l
for {
if s == n {
return s
}
s = s.Next
n = n.Next
}
}