Skip to content

Instantly share code, notes, and snippets.

@toravir
Created April 3, 2018 22:45
Show Gist options
  • Select an option

  • Save toravir/4414bb4b0b91e10f3081ed28568290fa to your computer and use it in GitHub Desktop.

Select an option

Save toravir/4414bb4b0b91e10f3081ed28568290fa to your computer and use it in GitHub Desktop.
Stack of arbitrary data
package stack
//Stack Object to store the items in the order of pushed..
type Stack struct {
elems []interface{}
top int
}
//NewStack will return a Stack object - on which you can perform
//Push, Pop, Peek, Size operations
func NewStack() Stack {
return Stack{make([]interface{}, 0, 50), -1}
}
//Push () pushes a data item onto the stack
func (s *Stack) Push(val interface{}) {
if s != nil {
s.elems = append(s.elems, val)
s.top++
}
return
}
//Pop removes and returns the most recently pushed item from the Stack
func (s *Stack) Pop() (val interface{}, ok bool) {
if s == nil {
return nil, false
}
if s.top >= 0 {
val := s.elems[s.top]
s.elems = s.elems[:s.top]
s.top--
return val, true
}
return nil, false
}
//Peek just returns the most recently pushed item from the Stack
func (s *Stack) Peek() (val interface{}, ok bool) {
if s == nil {
return nil, false
}
if s.top >= 0 {
val := s.elems[s.top]
return val, true
}
return nil, false
}
//Size returns the number of elements on the Stack
func (s *Stack) Size() (size int, ok bool) {
if s == nil {
return 0, false
}
return s.top + 1, true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment