-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
102 lines (89 loc) · 1.77 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
package gstack
import (
"bytes"
"fmt"
"iter"
)
type node[T any] struct {
Value T
Next *node[T]
}
// GStack is generic Stack implementation using linked list
type GStack[T any] struct {
top *node[T]
len int
}
// New creates an instance of GStack and pushes all given items to the created stack in reversed order
func New[T any](items ...T) GStack[T] {
s := GStack[T]{}
for _, item := range items {
s.Push(item)
}
return s
}
// Len returns the length of the stack
func (s *GStack[T]) Len() int {
return s.len
}
// Peek returns the top item without removing it or a zero object of given type
func (s *GStack[T]) Peek() T {
if s.top == nil {
var zero T
return zero
}
return s.top.Value
}
// Push puts the given item into the stack
func (s *GStack[T]) Push(item T) {
s.top = &node[T]{
Value: item,
Next: s.top,
}
s.len++
}
// Pop returns the top item and removes it from the stack or returns a zero object of given type
func (s *GStack[T]) Pop() T {
if s.top == nil {
var zero T
return zero
}
item := s.top.Value
s.top = s.top.Next
s.len--
return item
}
// String returns the list of all items in text format
func (s *GStack[T]) String() string {
if s.len == 0 {
return ""
}
var buf bytes.Buffer
top := s.top
for top != nil {
buf.WriteString(fmt.Sprintf("%v", top.Value))
if top.Next != nil {
buf.WriteString(", ")
}
top = top.Next
}
return buf.String()
}
// Clear clears the stack
func (s *GStack[T]) Clear() {
s.top = nil
s.len = 0
}
// Iter returns a consuming iterator for the stack
func (s *GStack[T]) Iter() iter.Seq[T] {
return func(yield func(T) bool) {
for s.top != nil {
if !yield(s.Pop()) {
break
}
}
}
}
// IsEmpty returns true if the stack is empty
func (s *GStack[T]) IsEmpty() bool {
return s.top == nil
}