-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
61 lines (51 loc) · 882 Bytes
/
stack.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
package BiG
import "fmt"
type Stack interface {
Pop() int32
Push(value int32)
Peek() int32
Size() int
}
type LinkedStack struct {
top *Element
size int
}
func NewStack() Stack {
return &LinkedStack{nil, 0}
}
func (ls *LinkedStack) String() string {
s := ""
e := ls.top
for i := 0; i < ls.Size(); i++ {
s += fmt.Sprintf(" %d|", e.value)
e = e.next
}
return s
}
type Element struct {
value int32
next *Element
}
func (ls *LinkedStack) Push(value int32) {
ls.top = &Element{value, ls.top}
ls.size++
//fmt.Println("PUSH:", ls)
}
func (ls *LinkedStack) Pop() int32 {
if ls.Size() == 0 {
return 0
}
defer func() {
ls.top = ls.top.next
ls.size--
}()
//fmt.Println("POP:", ls)
return ls.Peek()
}
func (ls *LinkedStack) Peek() int32 {
if ls.Size() == 0 {
return 0
}
return ls.top.value
}
func (ls LinkedStack) Size() int { return ls.size }