From 546ee9fe7cd0aaa624d9a39684b5c3532f309555 Mon Sep 17 00:00:00 2001 From: eson <474420502@qq.com> Date: Sat, 20 Jul 2019 03:55:45 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90stack=E7=9A=84=E5=8D=95?= =?UTF-8?q?=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- stack/stack.go | 6 +++ stack/stack_test.go | 99 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) diff --git a/stack/stack.go b/stack/stack.go index 1972a3c..df7c57b 100644 --- a/stack/stack.go +++ b/stack/stack.go @@ -33,6 +33,7 @@ func (as *Stack) Size() int { return as.size } +// String 从左到右 左边第一个表示Top 如链表 a(top)->b->c func (as *Stack) String() string { content := "" cur := as.top @@ -50,6 +51,11 @@ func (as *Stack) String() string { } func (as *Stack) Values() []interface{} { + + if as.size == 0 { + return nil + } + result := make([]interface{}, as.size, as.size) cur := as.top diff --git a/stack/stack_test.go b/stack/stack_test.go index 6571ffa..66e43ef 100644 --- a/stack/stack_test.go +++ b/stack/stack_test.go @@ -1,5 +1,104 @@ package lastack +import "testing" + +func TestBase(t *testing.T) { + s := New() + if !s.Empty() { + t.Error("stack not empty") + } + + if s.Size() != 0 { + t.Error("size != 0") + } + + if s.Values() != nil { + t.Error(s.Values()) + } +} + +func TestPush(t *testing.T) { + s := New() + + for i := 0; i < 5; i++ { + s.Push(i) + } + + if s.Empty() { + t.Error("stack is empty") + } + + if s.Size() == 0 { + t.Error("size == 0") + } + + if s.Values() == nil { + t.Error("Values() != nil") + } + + if s.String() != "4 3 2 1 0" { + t.Error(s.String()) + } + + if v, ok := s.Peek(); ok { + if v != 4 { + t.Error("why top != 4") + } + } else { + t.Error("not ok") + } + + if v, ok := s.Pop(); ok { + if v != 4 { + t.Error("why top != 4") + } + } else { + t.Error("not ok") + } + + if s.Size() != 4 { + t.Error("pop a element, size: 5 - 1 = 4") + } + + // + if v, ok := s.Pop(); ok { + if v != 3 { + t.Error("why top != 3") + } + } else { + t.Error("not ok") + } + + if s.Size() != 3 { + t.Error("pop a element, size: 4 - 1 = 3") + } + + for _, ok := s.Pop(); ok != false; _, ok = s.Pop() { + + } + + if !s.Empty() && s.Size() != 0 { + t.Error("pop all, stack should be empty") + } + + for i := 0; i < 5; i++ { + s.Push(i) + } + + if s.Size() != 5 { + t.Error("size != 5") + } + + s.Clear() + if !s.Empty() && s.Size() != 0 { + t.Error("pop all, stack should be empty") + } + + if v, ok := s.Peek(); v != nil || ok != false { + t.Error("should be v == nil and ok == false") + } +} + // func BenchmarkPush(b *testing.B) { // s := New() // b.N = 200000