-
Notifications
You must be signed in to change notification settings - Fork 44
/
util.go
60 lines (58 loc) · 952 Bytes
/
util.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package state
type stack []int
func newStack() *stack {
return &stack{}
}
func (stk *stack) last() int {
return len(*stk) - 1
}
func (stk *stack) peek() int {
if stk == nil || len(*stk) == 0 {
return -1
}
return (*stk)[stk.last()]
}
func (stk *stack) pop() int {
if stk == nil || len(*stk) == 0 {
return -1
}
lst := stk.last()
top := (*stk)[lst]
*stk = (*stk)[:lst]
return top
}
func (stk *stack) push(args ...int) *stack {
if stk == nil {
stk = &stack{}
}
*stk = append(*stk, args...)
return stk
}
func (stk *stack) export() []int {
size := len(*stk)
if size <= 0 {
return nil
}
buf := make([]int, size)
for i, v := range *stk {
buf[size-i-1] = v
}
return buf
}
func (stk *stack) get(index int) int {
if index < 0 {
return -1
}
return (*stk)[index]
}
func (stk *stack) iter() func() int {
next := stk.last()
return func() int {
if next < 0 {
return -1
}
idx := next
next--
return (*stk)[idx]
}
}