diff --git a/collections/list/array_list.go b/collections/list/array_list.go index 37c2daa..086b582 100644 --- a/collections/list/array_list.go +++ b/collections/list/array_list.go @@ -16,13 +16,32 @@ type ArrayList[T any] struct { func NewArrayList[T any](elems ...T) *ArrayList[T] { minCap := minCapacity + + size := len(elems) + for minCap < size { + minCap <<= 1 + } + + var tail int = size var buf []T - return &ArrayList[T]{ - buf: buf, - minCap: minCap, - list: list[T]{locker: locker.EmptyLocker}, + if len(elems) > 0 { + buf = make([]T, minCap) + copy(buf, elems) } + + l := &ArrayList[T]{ + list: list[T]{size: size, locker: locker.EmptyLocker}, + buf: buf, + tail: tail, + minCap: minCap, + } + + // for _, v := range elems { + // l.PushBack(v) + // } + + return l } func (l *ArrayList[T]) PushFront(v T) { diff --git a/collections/list/array_list_test.go b/collections/list/array_list_test.go index acdc097..3dcffb3 100644 --- a/collections/list/array_list_test.go +++ b/collections/list/array_list_test.go @@ -7,9 +7,12 @@ import ( ) func TestNewArrayList(t *testing.T) { - l := list.NewArrayList[int]() + l := list.NewArrayList(1, 2, 3) + + l.ForEach(func(i int) { + t.Log(i) + }) - _ = l } func TestArrayPushBack(t *testing.T) { diff --git a/collections/list/linked_list.go b/collections/list/linked_list.go index 8599c68..4240f77 100644 --- a/collections/list/linked_list.go +++ b/collections/list/linked_list.go @@ -16,10 +16,9 @@ type LinkedNode[T any] struct { // NewLinkedList 初始化链表 func NewLinkedList[T any](elems ...T) *LinkedList[T] { - l := - &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}) @@ -29,12 +28,18 @@ func NewLinkedList[T any](elems ...T) *LinkedList[T] { } func (l *LinkedList[T]) PushBack(v T) *LinkedList[T] { + l.locker.Lock() + defer l.locker.Unlock() + l.pushBackNode(&LinkedNode[T]{Value: v}) return l } func (l *LinkedList[T]) PushFront(v T) *LinkedList[T] { + l.locker.Lock() + defer l.locker.Unlock() + l.pushFrontNode(&LinkedNode[T]{Value: v}) return l @@ -130,9 +135,6 @@ func (l *LinkedList[T]) RemoveAt(index int) { } func (l *LinkedList[T]) pushBackNode(n *LinkedNode[T]) { - l.locker.Lock() - defer l.locker.Unlock() - n.Next = nil n.Prev = l.tail @@ -148,9 +150,6 @@ func (l *LinkedList[T]) pushBackNode(n *LinkedNode[T]) { } func (l *LinkedList[T]) pushFrontNode(n *LinkedNode[T]) { - l.locker.Lock() - defer l.locker.Unlock() - n.Next = l.front n.Prev = nil if l.front != nil {