forked from steger/pr3-ws202526
57 lines
958 B
Go
57 lines
958 B
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
func SlicesIndex[S []E, E comparable](s S, v E) int {
|
|
for i := range s {
|
|
if v == s[i] {
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
type List[T any] struct {
|
|
head, tail *element[T]
|
|
}
|
|
|
|
type element[T any] struct {
|
|
next *element[T]
|
|
val T
|
|
}
|
|
|
|
func (lst *List[T]) Push(v T) {
|
|
if lst.tail == nil {
|
|
lst.head = &element[T]{val: v}
|
|
lst.tail = lst.head
|
|
} else {
|
|
lst.tail.next = &element[T]{val: v}
|
|
lst.tail = lst.tail.next
|
|
}
|
|
}
|
|
|
|
func (lst *List[T]) AllElements() []T {
|
|
var elems []T
|
|
for e := lst.head; e != nil; e = e.next {
|
|
elems = append(elems, e.val)
|
|
}
|
|
return elems
|
|
}
|
|
|
|
func main() {
|
|
var s = []string{"foo", "bar", "zoo"}
|
|
fmt.Println("index of zoo:", SlicesIndex(s, "zoo"))
|
|
|
|
_ = SlicesIndex[[]string, string](s, "zoo")
|
|
|
|
var s2 = []int{2, 4, 5, 6}
|
|
fmt.Println("index of 4: ", SlicesIndex(s2, 4))
|
|
|
|
lst := List[float64]{}
|
|
lst.Push(10)
|
|
lst.Push(13)
|
|
lst.Push(23)
|
|
lst.Push(23.3)
|
|
fmt.Println("list:", lst.AllElements())
|
|
}
|