-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
65 lines (52 loc) · 892 Bytes
/
Copy pathstack.go
File metadata and controls
65 lines (52 loc) · 892 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
package ungo
import "fmt"
type stackNode[T any] struct {
val T
last *stackNode[T]
}
type Stack[T any] struct {
counter int
last *stackNode[T]
}
func NewStack[T any]() *Stack[T] {
return &Stack[T]{
counter: 0,
last: nil,
}
}
func (s *Stack[T]) String() string {
if s.last == nil {
return "Stack(empty)"
}
return fmt.Sprintf("Stack(last: %v)", s.last)
}
func (s *Stack[T]) Push(value T) {
nLast := &stackNode[T]{
val: value,
last: s.last,
}
s.last = nLast
s.counter++
}
func (s *Stack[T]) Pop() Optional[T] {
if s.last == nil {
return None[T]()
}
value := s.last.val
s.last = s.last.last
s.counter--
return Some(value)
}
func (s *Stack[T]) Peek() Optional[T] {
if s.last == nil {
return None[T]()
}
return Some(s.last.val)
}
func (s *Stack[T]) Size() int {
return s.counter
}
func (s *Stack[T]) Clear() {
for s.Pop().HasValue() {
}
}