forked from steger/pr3-ws202526
generics
parent
c11ff4321e
commit
0872d4f39d
|
|
@ -2,7 +2,7 @@ package main
|
||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
func SlicesIndex[S []E, E int](s []string, v string) int {
|
func SlicesIndex[S []E, E comparable](s S, v E) int {
|
||||||
for i := range s {
|
for i := range s {
|
||||||
if v == s[i] {
|
if v == s[i] {
|
||||||
return i
|
return i
|
||||||
|
|
@ -11,27 +11,27 @@ func SlicesIndex[S []E, E int](s []string, v string) int {
|
||||||
return -1
|
return -1
|
||||||
}
|
}
|
||||||
|
|
||||||
type List struct {
|
type List[T any] struct {
|
||||||
head, tail *element
|
head, tail *element[T]
|
||||||
}
|
}
|
||||||
|
|
||||||
type element struct {
|
type element[T any] struct {
|
||||||
next *element
|
next *element[T]
|
||||||
val int
|
val T
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lst *List) Push(v int) {
|
func (lst *List[T]) Push(v T) {
|
||||||
if lst.tail == nil {
|
if lst.tail == nil {
|
||||||
lst.head = &element{val: v}
|
lst.head = &element[T]{val: v}
|
||||||
lst.tail = lst.head
|
lst.tail = lst.head
|
||||||
} else {
|
} else {
|
||||||
lst.tail.next = &element{val: v}
|
lst.tail.next = &element[T]{val: v}
|
||||||
lst.tail = lst.tail.next
|
lst.tail = lst.tail.next
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lst *List) AllElements() []int {
|
func (lst *List[T]) AllElements() []T {
|
||||||
var elems []int
|
var elems []T
|
||||||
for e := lst.head; e != nil; e = e.next {
|
for e := lst.head; e != nil; e = e.next {
|
||||||
elems = append(elems, e.val)
|
elems = append(elems, e.val)
|
||||||
}
|
}
|
||||||
|
|
@ -40,12 +40,17 @@ func (lst *List) AllElements() []int {
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var s = []string{"foo", "bar", "zoo"}
|
var s = []string{"foo", "bar", "zoo"}
|
||||||
|
|
||||||
fmt.Println("index of zoo:", SlicesIndex(s, "zoo"))
|
fmt.Println("index of zoo:", SlicesIndex(s, "zoo"))
|
||||||
|
|
||||||
lst := List{}
|
_ = 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(10)
|
||||||
lst.Push(13)
|
lst.Push(13)
|
||||||
lst.Push(23)
|
lst.Push(23)
|
||||||
|
lst.Push(23.3)
|
||||||
fmt.Println("list:", lst.AllElements())
|
fmt.Println("list:", lst.AllElements())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue