forked from digisan/go-generics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
76 lines (66 loc) · 1.19 KB
/
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package gogenerics
import (
"fmt"
"strings"
)
type Stack[T any] []T
// *** Push
func (stk *Stack[T]) Push(items ...T) int {
*stk = append(*stk, items...)
return len(items)
}
// *** Len :
func (stk *Stack[T]) Len() int {
return len(*stk)
}
// *** Pop :
func (stk *Stack[T]) Pop() (T, bool) {
if stk.Len() > 0 {
last := (*stk)[stk.Len()-1]
*stk = (*stk)[:stk.Len()-1]
return last, true
}
return *new(T), false
}
// *** Peek :
func (stk *Stack[T]) Peek() (T, bool) {
if stk.Len() > 0 {
return (*stk)[stk.Len()-1], true
}
return *new(T), false
}
// *** Clear :
func (stk *Stack[T]) Clear() Stack[T] {
cp := stk.Copy()
*stk = Stack[T]{}
return cp
}
// *** Copy :
func (stk *Stack[T]) Copy() Stack[T] {
tmp := make([]T, stk.Len())
copy(tmp, *stk)
return Stack[T](tmp)
}
// *** Sink :
func (stk *Stack[T]) Sink() []T {
n := stk.Len()
arr := make([]T, 0, n)
for {
if ele, ok := stk.Pop(); ok {
arr = append(arr, ele)
} else {
break
}
}
return arr
}
// String :
func (stk Stack[T]) String() string {
sep := ","
sb := strings.Builder{}
for _, ele := range stk {
sb.WriteString(fmt.Sprintf("%v", ele))
sb.WriteString(sep)
}
return strings.TrimRight(sb.String(), sep)
}