-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.go
114 lines (98 loc) · 1.83 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package collections
import "container/list"
type Stack[T any] interface {
Push(val T)
Pop() T
Top() T
Size() int
}
type UnsafeStack[T any] struct {
elements *list.List
_padding0 [56]byte
}
func NewUnsafeStack[T any]() *UnsafeStack[T] {
return &UnsafeStack[T]{
elements: list.New(),
}
}
func (u UnsafeStack[T]) Push(val T) {
u.elements.PushBack(val)
}
func (u UnsafeStack[T]) Pop() (t T) {
v := u.elements.Back()
if v != nil {
u.elements.Remove(v)
t = v.Value.(T)
}
return
}
func (u UnsafeStack[T]) Top() (t T) {
v := u.elements.Back()
if v != nil {
t = v.Value.(T)
}
return
}
func (u UnsafeStack[T]) Size() int {
return u.elements.Len()
}
// UnsafeCompressedStack 非并发安全的Stack
type UnsafeCompressedStack[T Frame] struct {
elements *list.List
_padding0 [56]byte
count int
_padding1 [56]byte
}
type Frame interface {
Equals(value Frame) bool
Init()
ReEnter()
}
type stackElement[T Frame] struct {
val T
max int
count int
}
func NewUnsafeCompressedStack[T Frame]() *UnsafeCompressedStack[T] {
return &UnsafeCompressedStack[T]{
elements: list.New(),
}
}
func (s *UnsafeCompressedStack[T]) Push(val T) {
s.count++
back := s.elements.Back()
if back != nil {
ele := back.Value.(*stackElement[T])
if val.Equals(ele.val) {
ele.val.ReEnter()
ele.max++
ele.count++
return
}
}
val.Init()
s.elements.PushBack(&stackElement[T]{val: val, max: 1, count: 1})
}
func (s *UnsafeCompressedStack[T]) Pop() (t T) {
e := s.elements.Back()
if e != nil {
ele := e.Value.(*stackElement[T])
ele.count--
if ele.count == 0 {
s.elements.Remove(e)
}
s.count--
t = ele.val
}
return
}
func (s *UnsafeCompressedStack[T]) Top() (t T) {
e := s.elements.Back()
if e != nil {
t = e.Value.(*stackElement[T]).val
}
return
}
func (s *UnsafeCompressedStack[T]) Size() int {
return s.count
}