stack.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package diffmatchpatch
  2. import (
  3. "fmt"
  4. )
  5. type Stack struct {
  6. top *Element
  7. size int
  8. }
  9. type Element struct {
  10. value interface{}
  11. next *Element
  12. }
  13. // Len returns the stack's length
  14. func (s *Stack) Len() int {
  15. return s.size
  16. }
  17. // Push appends a new element onto the stack
  18. func (s *Stack) Push(value interface{}) {
  19. s.top = &Element{value, s.top}
  20. s.size++
  21. }
  22. // Pop removes the top element from the stack and return its value
  23. // If the stack is empty, return nil
  24. func (s *Stack) Pop() (value interface{}) {
  25. if s.size > 0 {
  26. value, s.top = s.top.value, s.top.next
  27. s.size--
  28. return
  29. }
  30. return nil
  31. }
  32. // Peek returns the value of the element on the top of the stack
  33. // but don't remove it. If the stack is empty, return nil
  34. func (s *Stack) Peek() (value interface{}) {
  35. if s.size > 0 {
  36. value = s.top.value
  37. return
  38. }
  39. return -1
  40. }
  41. // Clear empties the stack
  42. func (s *Stack) Clear() {
  43. s.top = nil
  44. s.size = 0
  45. }
  46. func main() {
  47. stack := new(Stack)
  48. stack.Push("Things")
  49. stack.Push("and")
  50. stack.Push("Stuff")
  51. for stack.Len() > 0 {
  52. fmt.Printf("%s ", stack.Pop().(string))
  53. }
  54. fmt.Println()
  55. }