-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
60 lines (49 loc) · 1.01 KB
/
stack.go
File metadata and controls
60 lines (49 loc) · 1.01 KB
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 htmlparser
type Stack[T any] struct {
items []T
}
func NewStack[T any]() *Stack[T] {
return &Stack[T]{items: make([]T, 0)}
}
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *Stack[T]) Pop() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
index := len(s.items) - 1
item := s.items[index]
s.items = s.items[:index]
return item, true
}
func (s *Stack[T]) Peek() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
return s.items[len(s.items)-1], true
}
func (s *Stack[T]) IsEmpty() bool {
return len(s.items) == 0
}
func (s *Stack[T]) Size() int {
return len(s.items)
}
func (s *Stack[T]) Clear() {
s.items = s.items[:0]
}
func (s *Stack[T]) ToSlice() []T {
result := make([]T, len(s.items))
copy(result, s.items)
return result
}
func FromSlice[T any](slice []T) *Stack[T] {
items := make([]T, len(slice))
copy(items, slice)
return &Stack[T]{items: items}
}
func (s *Stack[T]) Clone() *Stack[T] {
return FromSlice(s.items)
}