stack_arr.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. const LIMIT = 4
  7. type Stack [LIMIT]int
  8. func main() {
  9. st1 := new(Stack)
  10. fmt.Printf("%v\n", st1)
  11. st1.Push(3)
  12. fmt.Printf("%v\n", st1)
  13. st1.Push(7)
  14. fmt.Printf("%v\n", st1)
  15. st1.Push(10)
  16. fmt.Printf("%v\n", st1)
  17. st1.Push(99)
  18. fmt.Printf("%v\n", st1)
  19. p := st1.Pop()
  20. fmt.Printf("Popped %d\n", p)
  21. fmt.Printf("%v\n", st1)
  22. p = st1.Pop()
  23. fmt.Printf("Popped %d\n", p)
  24. fmt.Printf("%v\n", st1)
  25. p = st1.Pop()
  26. fmt.Printf("Popped %d\n", p)
  27. fmt.Printf("%v\n", st1)
  28. p = st1.Pop()
  29. fmt.Printf("Popped %d\n", p)
  30. fmt.Printf("%v\n", st1)
  31. }
  32. // put value on first position which contains 0, starting from bottom
  33. func (st *Stack) Push(n int) {
  34. for ix, v := range st {
  35. if v == 0 {
  36. st[ix] = n
  37. break
  38. }
  39. }
  40. }
  41. // take value from first position which contains !=0, starting from top
  42. func (st *Stack) Pop() int {
  43. v := 0
  44. for ix := len(st) - 1; ix >= 0; ix-- {
  45. if v = st[ix]; v != 0 {
  46. st[ix] = 0
  47. return v
  48. }
  49. }
  50. return 0
  51. }
  52. func (st Stack) String() string {
  53. str := ""
  54. for ix, v := range st {
  55. str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(v) + "] "
  56. }
  57. return str
  58. }