stack_struct.go 1014 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // stack_struct.go
  2. package main
  3. import (
  4. "fmt"
  5. "strconv"
  6. )
  7. const LIMIT = 4
  8. type Stack struct {
  9. ix int // first free position, so data[ix] == 0
  10. data [LIMIT]int
  11. }
  12. func main() {
  13. st1 := new(Stack)
  14. fmt.Printf("%v\n", st1)
  15. st1.Push(3)
  16. fmt.Printf("%v\n", st1)
  17. st1.Push(7)
  18. fmt.Printf("%v\n", st1)
  19. st1.Push(10)
  20. fmt.Printf("%v\n", st1)
  21. st1.Push(99)
  22. fmt.Printf("%v\n", st1)
  23. p := st1.Pop()
  24. fmt.Printf("Popped %d\n", p)
  25. fmt.Printf("%v\n", st1)
  26. p = st1.Pop()
  27. fmt.Printf("Popped %d\n", p)
  28. fmt.Printf("%v\n", st1)
  29. p = st1.Pop()
  30. fmt.Printf("Popped %d\n", p)
  31. fmt.Printf("%v\n", st1)
  32. p = st1.Pop()
  33. fmt.Printf("Popped %d\n", p)
  34. fmt.Printf("%v\n", st1)
  35. }
  36. func (st *Stack) Push(n int) {
  37. if st.ix+1 > LIMIT {
  38. return // stack is full!
  39. }
  40. st.data[st.ix] = n
  41. st.ix++
  42. }
  43. func (st *Stack) Pop() int {
  44. st.ix--
  45. return st.data[st.ix]
  46. }
  47. func (st Stack) String() string {
  48. str := ""
  49. for ix := 0; ix < st.ix; ix++ {
  50. str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "] "
  51. }
  52. return str
  53. }