-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstackTools.go
63 lines (58 loc) · 1.04 KB
/
stackTools.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
package go_utils
import (
"fmt"
"sync"
)
// 创建一个泛型的先进先出(FIFO)栈
type FIFOStack[T any] struct {
data []T
lk *sync.Mutex
PushHd bool
PopTail bool
}
func NewFIFOStack[T any]() *FIFOStack[T] {
return &FIFOStack[T]{lk: &sync.Mutex{}}
}
func (s *FIFOStack[T]) SetPush2Head() {
s.PushHd = true
}
func (s *FIFOStack[T]) SetPopTail() {
s.PopTail = true
}
// 入栈操作
func (s *FIFOStack[T]) Push(value ...T) {
s.lk.Lock()
defer s.lk.Unlock()
if s.PushHd {
s.data = append(value, s.data...)
} else {
s.data = append(s.data, value...)
}
}
func (s *FIFOStack[T]) Len() int {
return len(s.data)
}
func (s *FIFOStack[T]) Clean() {
s.lk.Lock()
defer s.lk.Unlock()
s.data = []T{}
}
// 出栈操作
func (s *FIFOStack[T]) Pop() (T, error) {
s.lk.Lock()
defer s.lk.Unlock()
var r T
if len(s.data) == 0 {
return r, fmt.Errorf("栈为空")
}
var value T
if s.PopTail {
n4 := len(s.data) - 1
value = s.data[n4]
s.data = s.data[:n4]
} else {
value = s.data[0]
s.data = s.data[1:]
}
return value, nil
}