This commit is contained in:
Gregory 2021-11-08 20:32:55 +02:00
commit 6f9dc7b91b
3 changed files with 87 additions and 0 deletions

View file

@ -0,0 +1,50 @@
package stack
// "Generic" item.
// When type parameters will land this type became
// type Item[T any] T
type Item interface{}
type Stack interface {
Push(Item)
Pop() Item
Size() int
IsEmpty() bool
}
// We use linked list as internal data structure
// to get O(1) speed for push and pop opeartions
type node struct {
item Item
next *node
}
type stack struct {
size int
head *node
}
func NewStack() Stack {
return &stack{}
}
func (s *stack) Push(item Item) {
next := s.head
s.head = &node{item, next}
s.size++
}
func (s *stack) Pop() Item {
head := s.head
s.head = head.next
s.size--
return head.item
}
func (s *stack) Size() int {
return s.size
}
func (s *stack) IsEmpty() bool {
return s.size == 0
}

View file

@ -0,0 +1,34 @@
package stack
import (
"log"
"testing"
)
func TestSimple(t *testing.T) {
stack := NewStack()
stack.Push(1)
stack.Push(2)
if stack.Pop().(int) != 2 {
log.Fatal("wrong stack value")
}
}
func TestSize(t *testing.T) {
stack := NewStack()
if !stack.IsEmpty() {
log.Fatal("should be empty")
}
stack.Push(1)
stack.Push(2)
stack.Push(3)
if stack.Size() != 3 {
log.Fatal("wrong size")
}
}

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module github.com/fotonmoton/algorithms
go 1.16