Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. package stack
  2.  
  3. type Stack struct {
  4. *node
  5. }
  6.  
  7. type node struct {
  8. value string
  9. next *node
  10. }
  11.  
  12. // New inits a new stack
  13. func New() *Stack {
  14. return &Stack{}
  15. }
  16.  
  17. // Push inserts an item to the stack
  18. // Complexity: O(1)
  19. func (s *Stack) Push(v string) {
  20. s.node = &node{value: v, next: s.node}
  21. }
  22.  
  23. // Pop removes the the last item from the stack
  24. // Complexity: O(1)
  25. func (s *Stack) Pop() string {
  26. n := s.node
  27. v := n.value
  28. s.node = n.next
  29. return v
  30. }
  31.  
  32. // IsEmpty checks the stack's emptiness
  33. // Complexity: O(1)
  34. func (s *Stack) IsEmpty() bool {
  35. return s.node == nil
  36. }
  37.  
  38. // Size returns the size of the stack
  39. // Complexity: O(n)
  40. func (s *Stack) Size() uint {
  41. if s.IsEmpty() {
  42. return 0
  43. }
  44. size := uint(1)
  45. t := s.node
  46. for t.next != nil {
  47. size++
  48. t = t.next
  49. }
  50.  
  51. return size
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement