stack_general.go 762 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // stack.go
  2. package stack
  3. import "errors"
  4. type Stack []interface{}
  5. func (stack Stack) Len() int {
  6. return len(stack)
  7. }
  8. func (stack Stack) Cap() int {
  9. return cap(stack)
  10. }
  11. func (stack Stack) IsEmpty() bool {
  12. return len(stack) == 0
  13. }
  14. func (stack *Stack) Push(e interface{}) {
  15. *stack = append(*stack, e)
  16. }
  17. func (stack Stack) Top() (interface{}, error) {
  18. if len(stack) == 0 {
  19. return nil, errors.New("stack is empty")
  20. }
  21. return stack[len(stack)-1], nil
  22. }
  23. func (stack *Stack) Pop() (interface{}, error) {
  24. stk := *stack // dereference to a local variable stk
  25. if len(stk) == 0 {
  26. return nil, errors.New("stack is empty")
  27. }
  28. top := stk[len(stk)-1]
  29. *stack = stk[:len(stk)-1] // shrink the stack
  30. return top, nil
  31. }