- add iterator to linked list stack

pull/12/head
Emir Pasic 8 years ago
parent 8e0280ece6
commit f35d68c85d

@ -33,6 +33,7 @@ package linkedliststack
import (
"fmt"
"github.com/emirpasic/gods/containers"
"github.com/emirpasic/gods/lists/singlylinkedlist"
"github.com/emirpasic/gods/stacks"
"strings"
@ -40,6 +41,7 @@ import (
func assertInterfaceImplementation() {
var _ stacks.Stack = (*Stack)(nil)
var _ containers.Iterator = (*Iterator)(nil)
}
type Stack struct {
@ -90,6 +92,29 @@ func (stack *Stack) Values() []interface{} {
return stack.list.Values()
}
type Iterator struct {
stack *Stack
index int
}
func (stack *Stack) Iterator() Iterator {
return Iterator{stack: stack, index: -1}
}
func (iterator *Iterator) Next() bool {
iterator.index += 1
return iterator.stack.withinRange(iterator.index)
}
func (iterator *Iterator) Value() interface{} {
value, _ := iterator.stack.list.Get(iterator.index) // in reverse (LIFO)
return value
}
func (iterator *Iterator) Index() interface{} {
return iterator.index
}
func (stack *Stack) String() string {
str := "LinkedListStack\n"
values := []string{}
@ -99,3 +124,8 @@ func (stack *Stack) String() string {
str += strings.Join(values, ", ")
return str
}
// Check that the index is withing bounds of the list
func (stack *Stack) withinRange(index int) bool {
return index >= 0 && index < stack.list.Size()
}

@ -84,7 +84,41 @@ func TestLinkedListStack(t *testing.T) {
if actualValue := stack.Values(); len(actualValue) != 0 {
t.Errorf("Got %v expected %v", actualValue, "[]")
}
}
func TestLinkedListStackIterator(t *testing.T) {
stack := New()
stack.Push("a")
stack.Push("b")
stack.Push("c")
// Iterator
it := stack.Iterator()
for it.Next() {
index := it.Index()
value := it.Value()
switch index {
case 0:
if actualValue, expectedValue := value, "c"; actualValue != expectedValue {
t.Errorf("Got %v expected %v", actualValue, expectedValue)
}
case 1:
if actualValue, expectedValue := value, "b"; actualValue != expectedValue {
t.Errorf("Got %v expected %v", actualValue, expectedValue)
}
case 2:
if actualValue, expectedValue := value, "a"; actualValue != expectedValue {
t.Errorf("Got %v expected %v", actualValue, expectedValue)
}
default:
t.Errorf("Too many")
}
}
stack.Clear()
it = stack.Iterator()
for it.Next() {
t.Errorf("Shouldn't iterate on empty stack")
}
}
func BenchmarkLinkedListStack(b *testing.B) {

Loading…
Cancel
Save