From a02f238ff1df8e03bfa4fd135d34d6c0b3bdbd89 Mon Sep 17 00:00:00 2001 From: huangsimin Date: Mon, 20 May 2019 19:12:38 +0800 Subject: [PATCH] =?UTF-8?q?ll=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- list/linkedlist/linkedlist.go | 3 ++- list/linkedlist/linkedlist_test.go | 26 ++++++++++++++++++++++++++ utils/math.go | 9 +++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 utils/math.go diff --git a/list/linkedlist/linkedlist.go b/list/linkedlist/linkedlist.go index f08a94d..8e93337 100644 --- a/list/linkedlist/linkedlist.go +++ b/list/linkedlist/linkedlist.go @@ -265,8 +265,9 @@ func (l *LinkedList) Remove(idx uint) (interface{}, bool) { panic(fmt.Sprintf("out of list range, size is %d, idx is %d", l.size, idx)) } + l.size-- if idx > l.size/2 { - idx = l.size - 1 - idx + idx = l.size - idx // l.size - 1 - idx // 尾部 for cur := l.tail.prev; cur != nil; cur = cur.prev { if idx == 0 { diff --git a/list/linkedlist/linkedlist_test.go b/list/linkedlist/linkedlist_test.go index 9a18cbe..9c6859e 100644 --- a/list/linkedlist/linkedlist_test.go +++ b/list/linkedlist/linkedlist_test.go @@ -175,10 +175,36 @@ func TestIndex(t *testing.T) { if _, ok := l.Index(5); ok { t.Error("[4 3 2 1 0] Index 5, out of range,ok = true is error") } + } func TestRemove(t *testing.T) { + l := New() + // "[4 3 2 1 0]" + for i := 0; i < 5; i++ { + l.PushFront(i) + } + l.Remove(0) + var result string + result = spew.Sprint(l.Values()) + if result != "[3 2 1 0]" { + t.Error("should be [3 2 1 0] but result is", result) + } + + l.Remove(3) + result = spew.Sprint(l.Values()) + if result != "[3 2 1]" { + t.Error("should be [3 2 1] but result is", result) + } + + defer func() { + if err := recover(); err == nil { + t.Error("should be out of range but is not") + } + }() + + l.Remove(3) } func BenchmarkPushBack(b *testing.B) { diff --git a/utils/math.go b/utils/math.go new file mode 100644 index 0000000..a66db91 --- /dev/null +++ b/utils/math.go @@ -0,0 +1,9 @@ +package utils + +var bit = uint(32 << (^uint(0) >> 63)) +var bitsub1 = bit - 1 + +func AbsInt(n int) uint { + y := n >> bitsub1 + return uint((n ^ y) - y) +}