forked from DinghaoLI/Coding-Interviews-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
38 lines (30 loc) · 771 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
package utils
import "errors"
type Stack []interface {}
func (stack Stack) Len() int {
return len(stack)
}
func (stack Stack) IsEmpty() bool {
return len(stack) == 0
}
func (stack Stack) Cap() int {
return cap(stack)
}
func (stack *Stack) Push(value interface{}) {
*stack = append(*stack, value)
}
func (stack Stack) Top() (interface{}, error) {
if len(stack) == 0 {
return nil, errors.New("Out of index, len is 0")
}
return stack[len(stack) - 1], nil
}
func (stack *Stack) Pop() (interface{}, error) {
theStack := *stack
if len(theStack) == 0 {
return nil, errors.New("Out of index, len is 0")
}
value := theStack[len(theStack) - 1]
*stack = theStack[:len(theStack) - 1]
return value, nil
}