forked from unknwon/the-way-to-go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_arr.go
executable file
·65 lines (58 loc) · 1.1 KB
/
stack_arr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"fmt"
"strconv"
)
const LIMIT = 4
type Stack [LIMIT]int
func main() {
st1 := new(Stack)
fmt.Printf("%v\n", st1)
st1.Push(3)
fmt.Printf("%v\n", st1)
st1.Push(7)
fmt.Printf("%v\n", st1)
st1.Push(10)
fmt.Printf("%v\n", st1)
st1.Push(99)
fmt.Printf("%v\n", st1)
p := st1.Pop()
fmt.Printf("Popped %d\n", p)
fmt.Printf("%v\n", st1)
p = st1.Pop()
fmt.Printf("Popped %d\n", p)
fmt.Printf("%v\n", st1)
p = st1.Pop()
fmt.Printf("Popped %d\n", p)
fmt.Printf("%v\n", st1)
p = st1.Pop()
fmt.Printf("Popped %d\n", p)
fmt.Printf("%v\n", st1)
}
// put value on first position which contains 0, starting from bottom
func (st *Stack) Push(n int) {
for ix, v := range st {
if v == 0 {
st[ix] = n
break
}
}
}
// take value from first position which contains !=0, starting from top
func (st *Stack) Pop() int {
v := 0
for ix := len(st) - 1; ix >= 0; ix-- {
if v = st[ix]; v != 0 {
st[ix] = 0
return v
}
}
return 0
}
func (st Stack) String() string {
str := ""
for ix, v := range st {
str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(v) + "] "
}
return str
}