diff options
author | Dimitri Sokolyuk <demon@dim13.org> | 2015-01-09 20:29:32 +0100 |
---|---|---|
committer | Dimitri Sokolyuk <demon@dim13.org> | 2015-01-09 20:29:32 +0100 |
commit | 876d05d5764485a42c9dd0f87c242dc8f355523a (patch) | |
tree | 9ec013d357a350e86561a5ffe219cbe598826fe7 | |
parent | 9bc1a2b8375f067dfb49a8c0ce5411510a338e05 (diff) |
Add more helper
-rw-r--r-- | stack.go | 18 | ||||
-rw-r--r-- | stack_test.go | 18 |
2 files changed, 36 insertions, 0 deletions
@@ -22,3 +22,21 @@ func (s *Stack) Pop() (v interface{}, ok bool) { } return v, ok } + +// Peek returns top value from Stack +func (s *Stack) Peek() interface{} { + return (*s)[len(*s) - 1] +} + +// Depth returns actual size of Stack +func (s *Stack) Depth() int { + return len(*s) +} + +// Swap swapes to top values +func (s *Stack) Swap() { + size := len(*s) + if size >= 2 { + (*s)[size-1], (*s)[size-2] = (*s)[size-2], (*s)[size-1] + } +} diff --git a/stack_test.go b/stack_test.go index 773f6cf..dec53cc 100644 --- a/stack_test.go +++ b/stack_test.go @@ -34,6 +34,24 @@ func TestMeny(t *testing.T) { } } +func TestSwap(t *testing.T) { + s := NewStack() + s.Push(1) + s.Push(2) + s.Swap() + if s.Depth() != 2 { + t.Error("Expected depth of 2") + } + a, _ := s.Pop() + b, _ := s.Pop() + if s.Depth() != 0 { + t.Error("Expected depth of 0") + } + if a != 1 || b != 2 { + t.Error("Expected swapped values") + } +} + func BenchmarkPushPopSingle(b *testing.B) { s := NewStack() for i := 0; i < b.N; i++ { |