-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathstack.go
44 lines (32 loc) · 788 Bytes
/
stack.go
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
41
42
43
44
package portal
import "github.com/pkg/errors"
var errStackIsEmpty = errors.New("stack is empty")
type stack struct {
elements []interface{}
}
func newStack() *stack {
return &stack{}
}
func (stack *stack) size() int {
return len(stack.elements)
}
func (stack *stack) push(x interface{}) {
if stack.elements == nil {
stack.elements = make([]interface{}, 0)
}
stack.elements = append(stack.elements, x)
}
func (stack *stack) top() (interface{}, error) {
if stack.size() == 0 {
return nil, errStackIsEmpty
}
return stack.elements[stack.size()-1], nil
}
func (stack *stack) pop() (interface{}, error) {
if stack.size() == 0 {
return nil, errStackIsEmpty
}
x := stack.elements[stack.size()-1]
stack.elements = stack.elements[0 : stack.size()-1]
return x, nil
}