1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00
This commit is contained in:
2022-11-21 16:18:54 +08:00
parent 1f8789e7eb
commit 04aecd4abc
3 changed files with 37 additions and 16 deletions

View File

@ -16,13 +16,32 @@ type ArrayList[T any] struct {
func NewArrayList[T any](elems ...T) *ArrayList[T] { func NewArrayList[T any](elems ...T) *ArrayList[T] {
minCap := minCapacity minCap := minCapacity
size := len(elems)
for minCap < size {
minCap <<= 1
}
var tail int = size
var buf []T var buf []T
return &ArrayList[T]{ if len(elems) > 0 {
buf: buf, buf = make([]T, minCap)
minCap: minCap, copy(buf, elems)
list: list[T]{locker: locker.EmptyLocker},
} }
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) { func (l *ArrayList[T]) PushFront(v T) {

View File

@ -7,9 +7,12 @@ import (
) )
func TestNewArrayList(t *testing.T) { 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) { func TestArrayPushBack(t *testing.T) {

View File

@ -16,8 +16,7 @@ type LinkedNode[T any] struct {
// NewLinkedList 初始化链表 // NewLinkedList 初始化链表
func NewLinkedList[T any](elems ...T) *LinkedList[T] { func NewLinkedList[T any](elems ...T) *LinkedList[T] {
l := l := &LinkedList[T]{
&LinkedList[T]{
list: list[T]{locker: locker.EmptyLocker}, list: list[T]{locker: locker.EmptyLocker},
} }
@ -29,12 +28,18 @@ func NewLinkedList[T any](elems ...T) *LinkedList[T] {
} }
func (l *LinkedList[T]) PushBack(v 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}) l.pushBackNode(&LinkedNode[T]{Value: v})
return l return l
} }
func (l *LinkedList[T]) PushFront(v T) *LinkedList[T] { func (l *LinkedList[T]) PushFront(v T) *LinkedList[T] {
l.locker.Lock()
defer l.locker.Unlock()
l.pushFrontNode(&LinkedNode[T]{Value: v}) l.pushFrontNode(&LinkedNode[T]{Value: v})
return l return l
@ -130,9 +135,6 @@ func (l *LinkedList[T]) RemoveAt(index int) {
} }
func (l *LinkedList[T]) pushBackNode(n *LinkedNode[T]) { func (l *LinkedList[T]) pushBackNode(n *LinkedNode[T]) {
l.locker.Lock()
defer l.locker.Unlock()
n.Next = nil n.Next = nil
n.Prev = l.tail n.Prev = l.tail
@ -148,9 +150,6 @@ func (l *LinkedList[T]) pushBackNode(n *LinkedNode[T]) {
} }
func (l *LinkedList[T]) pushFrontNode(n *LinkedNode[T]) { func (l *LinkedList[T]) pushFrontNode(n *LinkedNode[T]) {
l.locker.Lock()
defer l.locker.Unlock()
n.Next = l.front n.Next = l.front
n.Prev = nil n.Prev = nil
if l.front != nil { if l.front != nil {