-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implemented a simple stack for utility
- Loading branch information
1 parent
7381ff5
commit 5f31a86
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package util | ||
|
||
import "errors" | ||
|
||
var ( | ||
ErrStackEmpty = errors.New("stack is empty") | ||
) | ||
|
||
type Stack[T any] struct { | ||
data []T | ||
} | ||
|
||
func NewStack[T any]() *Stack[T] { | ||
return &Stack[T]{data: make([]T, 0)} | ||
} | ||
|
||
func (s *Stack[T]) Push(data T) { | ||
s.data = append(s.data, data) | ||
} | ||
|
||
func (s *Stack[T]) Pop() (T, error) { | ||
var data T | ||
if s.IsEmpty() { | ||
return data, ErrStackEmpty | ||
} | ||
|
||
data = s.data[len(s.data)-1] | ||
s.data = s.data[:len(s.data)-1] | ||
|
||
return data, nil | ||
} | ||
|
||
func (s *Stack[T]) IsEmpty() bool { | ||
return len(s.data) == 0 | ||
} | ||
|
||
func (s *Stack[T]) Peek() (T, error) { | ||
var data T | ||
|
||
if s.IsEmpty() { | ||
return data, ErrStackEmpty | ||
} | ||
|
||
data = s.data[len(s.data)-1] | ||
return data, nil | ||
} |