stack_general_v2.go 675 B

12345678910111213141516171819202122232425262728
  1. // stack_general_v2.go
  2. // Package collection implements a generic stack.
  3. package collection
  4. // The zero value for Stack is an empty stack ready to use.
  5. type Stack struct {
  6. data []interface{}
  7. }
  8. // Push adds x to the top of the stack.
  9. func (s *Stack) Push(x interface{}) {
  10. s.data = append(s.data, x)
  11. }
  12. // Pop removes and returns the top element of the stack.
  13. // It's a run-time error to call Pop on an empty stack.
  14. func (s *Stack) Pop() interface{} {
  15. i := len(s.data) - 1
  16. res := s.data[i]
  17. s.data[i] = nil // to avoid memory leak
  18. s.data = s.data[:i]
  19. return res
  20. }
  21. // Size returns the number of elements in the stack.
  22. func (s *Stack) Size() int {
  23. return len(s.data)
  24. }