-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathstack_array.go
More file actions
60 lines (52 loc) · 876 Bytes
/
stack_array.go
File metadata and controls
60 lines (52 loc) · 876 Bytes
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"
)
const ARRAY_SIZE = 10
//数组实现
type Stack struct {
data [ARRAY_SIZE]int
top int
lock sync.Mutex
}
func New() *Stack {
return &Stack{}
}
func (s *Stack) Len() int {
s.lock.Lock()
defer s.lock.Unlock()
return s.top
}
func (s *Stack) IsEmpty() bool {
s.lock.Lock()
defer s.lock.Unlock()
return s.top == 0
}
func (s *Stack) Push(i int) error {
s.lock.Lock()
defer s.lock.Unlock()
if s.top == ARRAY_SIZE {
return errors.New("栈已满")
}
s.data[s.top] = i
s.top++
return nil
}
func (s *Stack) Pop() (int, error) {
s.lock.Lock()
defer s.lock.Unlock()
if s.top == 0 {
return 0, errors.New("栈空")
}
s.top--
return s.data[s.top], nil
}
func (s *Stack) Peek() (int, error) {
s.lock.Lock()
defer s.lock.Unlock()
if s.top == 0 {
return 0, errors.New("栈空")
}
return s.data[s.top-1], nil
}