-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
39 lines (30 loc) · 816 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
/*
A simple naive implementation of a stack using a slice.
*/
package stack
import "errors"
// Stack is a simple LIFO stack for any type.
type Stack []interface{}
// Push adds an item to the top of the stack
func (s *Stack) Push(item interface{}) {
*s = append(*s, item)
}
// Pop removes the top item from the stack and returns it. An error is returned
// if called on an empty stack.
func (s *Stack) Pop() (interface{}, error) {
length := s.Length()
if length == 0 {
return nil, errors.New("Cannot pop from empty stack")
}
item := (*s)[length-1]
*s = (*s)[:length-1]
return item, nil
}
// Length is a wrapper for `len(s)`
func (s *Stack) Length() int {
return len(*s)
}
// IsEmpty returns true if the stack is empty, and false otherwise
func (s *Stack) IsEmpty() bool {
return s.Length() == 0
}