-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack.go
More file actions
40 lines (33 loc) · 665 Bytes
/
stack.go
File metadata and controls
40 lines (33 loc) · 665 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package preditor
import "errors"
type Stack[T any] struct {
data []T
size int
}
func NewStack[T any](size int) *Stack[T] {
return &Stack[T]{data: make([]T, size), size: size}
}
var (
EmptyStack = errors.New("empty stack")
)
func (s *Stack[T]) Pop() (T, error) {
if len(s.data) == 0 {
return *new(T), EmptyStack
}
last := s.data[len(s.data)-1]
s.data = s.data[:len(s.data)-1]
return last, nil
}
func (s *Stack[T]) Top() (T, error) {
if len(s.data) == 0 {
return *new(T), EmptyStack
}
last := s.data[len(s.data)-1]
return last, nil
}
func (s *Stack[T]) Push(e T) {
s.data = append(s.data, e)
if len(s.data) > s.size {
s.data = []T{e}
}
}