Reduce alllocations done by the stack

This commit is contained in:
Vikram Rangnekar
2019-06-16 20:51:36 -04:00
parent 45c283f2a7
commit cd6d6f97a8
3 changed files with 36 additions and 37 deletions

View File

@ -1,49 +1,47 @@
package util
type (
Stack struct {
top *StackNode
length int
}
StackNode struct {
value interface{}
prev *StackNode
}
)
type Stack struct {
stA [20]interface{}
st []interface{}
top int
}
// Create a new Stack
func NewStack() *Stack {
return &Stack{nil, 0}
s := &Stack{top: -1}
s.st = s.stA[:0]
return s
}
// Return the number of items in the Stack
func (this *Stack) Len() int {
return this.length
func (s *Stack) Len() int {
return (s.top + 1)
}
// View the top item on the Stack
func (this *Stack) Peek() interface{} {
if this.length == 0 {
return nil
func (s *Stack) Peek() interface{} {
if s.top == -1 {
return -1
}
return this.top.value
return s.st[s.top]
}
// Pop the top item of the Stack and return it
func (this *Stack) Pop() interface{} {
if this.length == 0 {
return nil
func (s *Stack) Pop() interface{} {
if s.top == -1 {
return -1
}
n := this.top
this.top = n.prev
this.length--
return n.value
s.top--
return s.st[(s.top + 1)]
}
// Push a value onto the top of the Stack
func (this *Stack) Push(value interface{}) {
n := &StackNode{value, this.top}
this.top = n
this.length++
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
}
}