stack.go 706 B

1234567891011121314151617181920212223242526272829303132333435
  1. // Stack implementation from
  2. // https://gist.github.com/bemasher/1777766
  3. package main
  4. type Stack struct {
  5. top *Element
  6. size int
  7. }
  8. type Element struct {
  9. value interface{} // All types satisfy the empty interface, so we can store anything here.
  10. next *Element
  11. }
  12. // Return the stack's length
  13. func (s *Stack) Len() int {
  14. return s.size
  15. }
  16. // Push a new element onto the stack
  17. func (s *Stack) Push(value interface{}) {
  18. s.top = &Element{value, s.top}
  19. s.size++
  20. }
  21. // Remove the top element from the stack and return it's value
  22. // If the stack is empty, return nil
  23. func (s *Stack) Pop() (value interface{}) {
  24. if s.size > 0 {
  25. value, s.top = s.top.value, s.top.next
  26. s.size--
  27. return
  28. }
  29. return nil
  30. }