Created
November 26, 2021 15:43
-
-
Save nikolaydubina/9dff30c265033a66f22e290f4b36e493 to your computer and use it in GitHub Desktop.
check_cycle_in_inifinite_single_linked_list.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ππππππππ¦π¦π¦π¦π¦π¦π¦π¦π¦π π»πππππππ | |
// time: O(N) | |
// space: O(1) | |
// Go Playground: https://go.dev/play/p/1g8m82vmuuu | |
// why: Merry Christmas! | |
package main | |
import "fmt" | |
type Node struct { | |
V string | |
Next *Node | |
} | |
func hasCycle(l *Node) bool { | |
if l == nil { | |
return false | |
} | |
for two, one, i := l, l.Next, 0; one != nil; i++ { | |
if one == two { | |
return true | |
} | |
one = one.Next | |
if (i % 2) == 1 { | |
two = two.Next | |
} | |
} | |
return false | |
} | |
func main() { | |
a := Node{V: "π₯₯"} | |
b := Node{V: "π "} | |
a.Next = &b | |
b.Next = &a | |
tests := []struct { | |
l *Node | |
hasCycle bool | |
}{ | |
{ | |
l: nil, | |
hasCycle: false, | |
}, | |
{ | |
l: &Node{V: "π", Next: &Node{V: "π π»", Next: &Node{V: "π¦"}}}, | |
hasCycle: false, | |
}, | |
{ | |
l: &a, | |
hasCycle: true, | |
}, | |
{ | |
l: &b, | |
hasCycle: true, | |
}, | |
} | |
for i, tc := range tests { | |
fmt.Printf("%d: expected(%t) got(%t), is it okay? %t\n", i, tc.hasCycle, hasCycle(tc.l), tc.hasCycle == hasCycle(tc.l)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment