gitlab.com/beacon-software/gadget@v0.0.0-20181217202115-54565ea1ed5e/collection/stack.go (about) 1 package collection 2 3 // Stack is an implementation of a stack (filo/lifo) datastructure 4 type Stack interface { 5 // Size of the stack represented as a count of the elements in the stack. 6 Size() int 7 // Push a new data element onto the stack. 8 Push(data interface{}) 9 // Pop the most recently pushed data element off the stack. 10 Pop() (interface{}, error) 11 // Peek returns the most recently pushed element without modifying the stack 12 Peek() (interface{}, error) 13 } 14 15 // stack is a threadsafe implementation of a stack datastructure 16 type stack struct { 17 list List 18 } 19 20 // NewStack that is empty. 21 func NewStack() Stack { 22 return &stack{list: NewList()} 23 } 24 25 // Size of the stack represented as a count of the elements in the stack. 26 func (s *stack) Size() int { return s.list.Size() } 27 28 // Push a new data element onto the stack. 29 func (s *stack) Push(data interface{}) { 30 s.list.InsertNext(nil, data) 31 } 32 33 // Pop the most recently pushed data element off the stack. 34 func (s *stack) Pop() (data interface{}, err error) { 35 return s.list.RemoveNext(nil) 36 } 37 38 // Peek returns the most recently pushed element without modifying the stack 39 func (s stack) Peek() (interface{}, error) { 40 if s.list.Size() == 0 { 41 return nil, NewEmptyListError() 42 } 43 return s.list.Head().Data(), nil 44 }