-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
68 lines (56 loc) · 992 Bytes
/
stack.go
File metadata and controls
68 lines (56 loc) · 992 Bytes
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
package stack
import (
"fmt"
"strings"
)
type Stack[T any] struct {
data []T
idx int
}
// New Stack
func New[T any]() *Stack[T] {
return &Stack[T]{idx: -1}
}
// Top returns top element
func (s *Stack[T]) Top() T {
return s.data[s.idx]
}
// Push given element `a` into stack
func (s *Stack[T]) Push(a T) {
s.idx++
if s.idx < len(s.data) {
s.data[s.idx] = a
} else {
s.data = append(s.data, a)
}
}
// Pop element from stack,
// return `nil` when stack is empty.
func (s *Stack[T]) Pop() (v T, ok bool) {
if s.idx > -1 {
s.idx--
return s.data[s.idx+1], true
}
return *new(T), false
}
func (s *Stack[T]) Size() int {
fmt.Println(s.idx)
if s.idx == -1 {
return 0
}
return s.idx
}
func (s *Stack[T]) String() string {
if s.idx < 1 {
return ""
}
b := strings.Builder{}
for i := 0; i <= s.idx; i++ {
if i == 0 {
b.WriteString(fmt.Sprintf("%v", s.data[i]))
} else {
b.WriteString(", " + fmt.Sprintf("%v", s.data[i]))
}
}
return b.String()
}