From 6f9dc7b91ba5c5022438b9d6872cc458e993aa2f Mon Sep 17 00:00:00 2001 From: Gregory Date: Mon, 8 Nov 2021 20:32:55 +0200 Subject: [PATCH] init --- fundamentals/stack/stack.go | 50 ++++++++++++++++++++++++++++++++ fundamentals/stack/stack_test.go | 34 ++++++++++++++++++++++ go.mod | 3 ++ 3 files changed, 87 insertions(+) create mode 100644 fundamentals/stack/stack.go create mode 100644 fundamentals/stack/stack_test.go create mode 100644 go.mod diff --git a/fundamentals/stack/stack.go b/fundamentals/stack/stack.go new file mode 100644 index 0000000..d94296e --- /dev/null +++ b/fundamentals/stack/stack.go @@ -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 +} diff --git a/fundamentals/stack/stack_test.go b/fundamentals/stack/stack_test.go new file mode 100644 index 0000000..d7c443a --- /dev/null +++ b/fundamentals/stack/stack_test.go @@ -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") + } + +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..44584f2 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/fotonmoton/algorithms + +go 1.16