From 089acbcc346904924e44fde4e3cdf9fbf7a6c526 Mon Sep 17 00:00:00 2001 From: eson <474420502@qq.com> Date: Thu, 6 Jun 2019 02:17:35 +0800 Subject: [PATCH] =?UTF-8?q?arraylist=20remove=20=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- list/arraylist/arraylist.go | 15 ++++++++--- list/arraylist/arraylist_test.go | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/list/arraylist/arraylist.go b/list/arraylist/arraylist.go index 89f58b7..5cae300 100644 --- a/list/arraylist/arraylist.go +++ b/list/arraylist/arraylist.go @@ -47,7 +47,7 @@ func (l *ArrayList) Size() uint { func (l *ArrayList) shrink() { if l.size <= listMinLimit { - log.Panic("list size is over listMaxLimit", listMinLimit) + return } if l.size <= l.shrinkSize { @@ -137,7 +137,7 @@ func (l *ArrayList) Index(idx uint) (interface{}, bool) { func (l *ArrayList) Remove(idx uint) (result interface{}, isfound bool) { - if idx < l.size { + if idx >= l.size { return nil, false } @@ -145,9 +145,16 @@ func (l *ArrayList) Remove(idx uint) (result interface{}, isfound bool) { isfound = true result = l.data[offset] - l.data[offset] = nil // cleanup reference + // l.data[offset] = nil // cleanup reference + + if l.size-l.tidx > l.hidx { + copy(l.data[offset:], l.data[offset+1:l.tidx]) // shift to the left by one (slow operation, need ways to optimize this) + l.tidx-- + } else { + copy(l.data[l.hidx+2:], l.data[l.hidx+1:offset]) + l.hidx++ + } - copy(l.data[offset:], l.data[idx+1:l.size]) // shift to the left by one (slow operation, need ways to optimize this) l.size-- l.shrink() diff --git a/list/arraylist/arraylist_test.go b/list/arraylist/arraylist_test.go index c1dcca3..b8c7ef5 100644 --- a/list/arraylist/arraylist_test.go +++ b/list/arraylist/arraylist_test.go @@ -95,3 +95,49 @@ func TestPop(t *testing.T) { t.Error("should not be ok, v = ", v) } } + +func TestRemove(t *testing.T) { + l := New() + for i := 0; i < 5; i++ { + l.PushFront(uint(i)) + } + + var result string + + for _, selval := range []uint{4, 3} { + last, _ := l.Index(selval) + if v, isfound := l.Remove(selval); isfound { + if v != last { + t.Error(v, " != ", last) + } + } else { + t.Error("should be found") + } + } + + result = spew.Sprint(l.Values()) + if result != "[4 3 2]" { + t.Error("should be [4 3 2], value =", result) + } + + v, _ := l.Remove(1) + if v != uint(3) { + t.Error(v) + } + + v, _ = l.Remove(1) + if v != uint(2) { + t.Error(v) + } + + v, _ = l.Remove(1) + if v != nil && l.Size() != 1 { + t.Error(v) + } + + v, _ = l.Remove(0) + if v != uint(4) && l.Size() != 0 { + t.Error(v, "size = ", l.Size()) + } + +}