stack.go 942 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package util
  2. type stackNode[T any] struct {
  3. value T
  4. previous *stackNode[T]
  5. }
  6. type Stack[T any] struct {
  7. top *stackNode[T]
  8. length int
  9. }
  10. // NewStack creates a new Stack[T]
  11. func NewStack[T any]() *Stack[T] {
  12. return &Stack[T]{
  13. top: nil,
  14. length: 0,
  15. }
  16. }
  17. // Push adds a value to the top of the stack.
  18. func (s *Stack[T]) Push(value T) {
  19. n := &stackNode[T]{
  20. value: value,
  21. previous: s.top,
  22. }
  23. s.top = n
  24. s.length++
  25. }
  26. // Pop the top item of the stack and return it
  27. func (s *Stack[T]) Pop() T {
  28. if s.length == 0 {
  29. return defaultFor[T]()
  30. }
  31. n := s.top
  32. s.top = n.previous
  33. s.length--
  34. return n.value
  35. }
  36. // Top returns the item on the top of the stack
  37. func (s *Stack[T]) Top() T {
  38. if s.length == 0 {
  39. return defaultFor[T]()
  40. }
  41. return s.top.value
  42. }
  43. // Length returns the total number of elements on the stack.
  44. func (s *Stack[T]) Length() int {
  45. return s.length
  46. }
  47. func defaultFor[T any]() T {
  48. var t T
  49. return t
  50. }