-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_array.go
58 lines (49 loc) · 1000 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
package level1
import (
"errors"
)
func NewStack1[T any](maxNum int) *Stack1[T]{
slice := make([]T, maxNum)
return &Stack1[T]{
MaxNum:maxNum,
Array:slice,
Top:0,
}
}
type Stack1[T any] struct {
MaxNum int
Array []T
Top int //栈顶上的位置
}
func (this *Stack1[T]) Push(val T) error {
if this.IsFull() {
this.ExpandCap(this.MaxNum)
}
this.Array[this.Top] = val
this.Top++
return nil
}
func (this *Stack1[T]) Pop() (val T, err error) {
val, err = this.Peek()
if err == nil {
this.Top--
}
return val, err
}
func (this *Stack1[T]) Peek() (val T, err error) {
if this.IsEmpty() {
return val, errors.New("stack empty")
}
return this.Array[this.Top-1], nil
}
func (this *Stack1[T]) IsFull() bool {
return this.MaxNum == this.Top
}
func (this *Stack1[T]) IsEmpty() bool {
return this.Top == 0
}
func (this *Stack1[T]) ExpandCap(size int) {
tmpArray := make([]T, this.MaxNum+size)
this.Array = append(this.Array, tmpArray ...)
this.MaxNum = this.MaxNum+size
}