super-graph/util/stack.go

48 lines
746 B
Go
Raw Normal View History

2019-03-24 14:57:29 +01:00
package util
2019-06-17 02:51:36 +02:00
type Stack struct {
stA [20]interface{}
st []interface{}
top int
}
2019-03-24 14:57:29 +01:00
// Create a new Stack
func NewStack() *Stack {
2019-06-17 02:51:36 +02:00
s := &Stack{top: -1}
s.st = s.stA[:0]
return s
2019-03-24 14:57:29 +01:00
}
// Return the number of items in the Stack
2019-06-17 02:51:36 +02:00
func (s *Stack) Len() int {
return (s.top + 1)
2019-03-24 14:57:29 +01:00
}
// View the top item on the Stack
2019-06-17 02:51:36 +02:00
func (s *Stack) Peek() interface{} {
if s.top == -1 {
return -1
2019-03-24 14:57:29 +01:00
}
2019-06-17 02:51:36 +02:00
return s.st[s.top]
2019-03-24 14:57:29 +01:00
}
// Pop the top item of the Stack and return it
2019-06-17 02:51:36 +02:00
func (s *Stack) Pop() interface{} {
if s.top == -1 {
return -1
2019-03-24 14:57:29 +01:00
}
2019-06-17 02:51:36 +02:00
s.top--
return s.st[(s.top + 1)]
2019-03-24 14:57:29 +01:00
}
// Push a value onto the top of the Stack
2019-06-17 02:51:36 +02:00
func (s *Stack) Push(value interface{}) {
s.top++
if len(s.st) <= s.top {
s.st = append(s.st, value)
} else {
s.st[s.top] = value
}
2019-03-24 14:57:29 +01:00
}