- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
Latest commit
39 lines (30 loc) · 816 Bytes
/
Copy pathstack.go
File metadata and controls
39 lines (30 loc) · 816 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
/*
A simple naive implementation of a stack using a slice.
*/
package stack
import"errors"
// Stack is a simple LIFO stack for any type.
typeStack []interface{}
// Push adds an item to the top of the stack
func (s*Stack) Push(iteminterface{}) {
*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()
iflength==0 {
returnnil, errors.New("Cannot pop from empty stack")
}
item:= (*s)[length-1]
*s= (*s)[:length-1]
returnitem, nil
}
// Length is a wrapper for `len(s)`
func (s*Stack) Length() int {
returnlen(*s)
}
// IsEmpty returns true if the stack is empty, and false otherwise
func (s*Stack) IsEmpty() bool {
returns.Length() ==0
}