- Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathstack_array.go
60 lines (52 loc) · 876 Bytes
/
stack_array.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
package stack
import (
"errors"
"sync"
)
constARRAY_SIZE=10
//数组实现
typeStackstruct {
data [ARRAY_SIZE]int
topint
lock sync.Mutex
}
funcNew() *Stack {
return&Stack{}
}
func (s*Stack) Len() int {
s.lock.Lock()
defers.lock.Unlock()
returns.top
}
func (s*Stack) IsEmpty() bool {
s.lock.Lock()
defers.lock.Unlock()
returns.top==0
}
func (s*Stack) Push(iint) error {
s.lock.Lock()
defers.lock.Unlock()
ifs.top==ARRAY_SIZE {
returnerrors.New("栈已满")
}
s.data[s.top] =i
s.top++
returnnil
}
func (s*Stack) Pop() (int, error) {
s.lock.Lock()
defers.lock.Unlock()
ifs.top==0 {
return0, errors.New("栈空")
}
s.top--
returns.data[s.top], nil
}
func (s*Stack) Peek() (int, error) {
s.lock.Lock()
defers.lock.Unlock()
ifs.top==0 {
return0, errors.New("栈空")
}
returns.data[s.top-1], nil
}