mved stack into linear category
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package stack
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Stack a Stack with no size
|
||||
type Stack[T any] struct {
|
||||
Capasity int
|
||||
Container []T
|
||||
}
|
||||
|
||||
// StackFixed creates Stack with a fixed size
|
||||
func StackFixed[T any](value int) *Stack[T] {
|
||||
|
||||
return &Stack[T]{
|
||||
Capasity: value,
|
||||
Container: make([]T, 0, value),
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Push Appends value to stack returns error
|
||||
// If using StackFixed errors when over capasity
|
||||
func (s *Stack[T]) Push(value T) error {
|
||||
if s.Capasity > 0 && (len(s.Container) >= s.Capasity) {
|
||||
return errors.New("Error max capasity exeded")
|
||||
}
|
||||
|
||||
s.Container = append(s.Container, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Pop returns value,error and removes last index
|
||||
func (s *Stack[T]) Pop() (T, error) {
|
||||
|
||||
var zero T
|
||||
|
||||
if len(s.Container) <= 0 {
|
||||
return zero, errors.New("Error Empty Stack")
|
||||
}
|
||||
|
||||
last := s.Container[len(s.Container)-1]
|
||||
s.Container = s.Container[:len(s.Container)-1]
|
||||
|
||||
return last, nil
|
||||
}
|
||||
|
||||
// Clear clears the stack
|
||||
func (s *Stack[T]) Clear() {
|
||||
s.Container = []T{}
|
||||
}
|
||||
|
||||
// Peek returns top item
|
||||
func (s *Stack[T]) Peek() T {
|
||||
return s.Container[len(s.Container)-1]
|
||||
}
|
||||
|
||||
// First returns bottom item
|
||||
func (s *Stack[T]) First() T {
|
||||
return s.Container[0]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package stack
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPush(t *testing.T) {
|
||||
s := Stack[int]{}
|
||||
s.Push(1)
|
||||
s.Push(2)
|
||||
s.Push(3)
|
||||
|
||||
if len(s.Container) != 3 {
|
||||
t.Errorf("expected 2 items, got %d", len(s.Container))
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user