diff --git a/collections/list/linked_list.go b/collections/list/linked_list.go index 2882eae..177a820 100644 --- a/collections/list/linked_list.go +++ b/collections/list/linked_list.go @@ -15,9 +15,16 @@ type LinkedNode[T any] struct { } func NewLinkedList[T any](elems ...T) *LinkedList[T] { - return &LinkedList[T]{ - list: list[T]{locker: locker.EmptyLocker}, + l := + &LinkedList[T]{ + list: list[T]{locker: locker.EmptyLocker}, + } + + for _, e := range elems { + l.pushBackNode(&LinkedNode[T]{Value: e}) } + + return l } func (l *LinkedList[T]) PushBack(v T) *LinkedList[T] { @@ -62,6 +69,20 @@ func (l *LinkedList[T]) ForEach(fn func(T) bool) { } } +func (l *LinkedList[T]) GetAt(i int) T { + if i <= l.Size() { + var n int + for current := l.front; current != nil; current = current.Next { + if n == i { + return current.Value + } + n++ + } + } + + return *new(T) +} + func (l *LinkedList[T]) Remove(n *LinkedNode[T]) { l.locker.Lock() defer l.locker.Unlock() diff --git a/collections/list/linked_list_test.go b/collections/list/linked_list_test.go index da430bd..78bb811 100644 --- a/collections/list/linked_list_test.go +++ b/collections/list/linked_list_test.go @@ -85,3 +85,14 @@ func BenchmarkLinkedList(b *testing.B) { l.PushBack(i) } } + +func TestRemoveNode(t *testing.T) { + l := list.NewLinkedList(1, 2, 4) + + l.ForEach(func(i int) bool { + t.Log(i) + + return false + }) + +}