show last element in stack string

This commit is contained in:
sentriz
2019-07-01 13:13:26 +01:00
parent b27d7e7aab
commit e517c7538c
5 changed files with 110 additions and 108 deletions

61
scanner/stack/stack.go Normal file
View File

@@ -0,0 +1,61 @@
package stack
import (
"fmt"
"strings"
"github.com/sentriz/gonic/model"
)
type item struct {
value *model.Album
next *item
}
type Stack struct {
top *item
len uint
}
func (s *Stack) Push(v *model.Album) {
s.top = &item{
value: v,
next: s.top,
}
s.len++
}
func (s *Stack) Pop() *model.Album {
if s.len == 0 {
return nil
}
v := s.top.value
s.top = s.top.next
s.len--
return v
}
func (s *Stack) Peek() *model.Album {
if s.len == 0 {
return nil
}
return s.top.value
}
func (s *Stack) PeekID() int {
if s.len == 0 {
return 0
}
return s.top.value.ID
}
func (s *Stack) String() string {
var str strings.Builder
str.WriteString("[")
for i, f := uint(0), s.top; i < s.len; i++ {
str.WriteString(fmt.Sprintf("%d, ", f.value.ID))
f = f.next
}
str.WriteString("]")
return str.String()
}

View File

@@ -0,0 +1,40 @@
package stack
import (
"testing"
"github.com/sentriz/gonic/model"
)
func egAlbum(id int) *model.Album {
return &model.Album{IDBase: model.IDBase{id}}
}
func TestFolderStack(t *testing.T) {
sta := &Stack{}
sta.Push(egAlbum(3))
sta.Push(egAlbum(4))
sta.Push(egAlbum(5))
sta.Push(egAlbum(6))
expected := "[6, 5, 4, 3, ]"
actual := sta.String()
if expected != actual {
t.Errorf("first stack: expected string %q, got %q",
expected, actual)
}
//
sta = &Stack{}
sta.Push(egAlbum(27))
sta.Push(egAlbum(4))
sta.Peek()
sta.Push(egAlbum(5))
sta.Push(egAlbum(6))
sta.Push(egAlbum(7))
sta.Pop()
expected = "[6, 5, 4, 27, ]"
actual = sta.String()
if expected != actual {
t.Errorf("second stack: expected string %q, got %q",
expected, actual)
}
}