init
This commit is contained in:
commit
6f9dc7b91b
3 changed files with 87 additions and 0 deletions
50
fundamentals/stack/stack.go
Normal file
50
fundamentals/stack/stack.go
Normal 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
|
||||
}
|
34
fundamentals/stack/stack_test.go
Normal file
34
fundamentals/stack/stack_test.go
Normal 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
3
go.mod
Normal file
|
@ -0,0 +1,3 @@
|
|||
module github.com/fotonmoton/algorithms
|
||||
|
||||
go 1.16
|
Loading…
Reference in a new issue