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