-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
36 lines (30 loc) · 720 Bytes
/
stack.go
File metadata and controls
36 lines (30 loc) · 720 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
package stack
import "errors"
type Stack[T any] struct {
store []T
top int
}
func NewStack[T any](len int) *Stack[T] {
return &Stack[T]{top: -1, store: make([]T, len)}
}
// Empty returns true if stack is empty, false otherwise
// Time = O(1), Space = O(1)
func (s *Stack[T]) Empty() bool {
return s.top == -1
}
// Push pushes an item at the top of the stack
// Time = O(1), Space = O(1)
func (s *Stack[T]) Push(item T) {
s.top += 1
s.store[s.top] = item
}
// Pop returns a top item from the stack, or error if stack is empty
// Time = O(1), Space = O(1)
func (s *Stack[T]) Pop() (T, error) {
if s.Empty() {
var t T
return t, errors.New("stack is empty")
}
s.top -= 1
return s.store[s.top+1], nil
}