-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
63 lines (52 loc) · 1.17 KB
/
stack.go
File metadata and controls
63 lines (52 loc) · 1.17 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
61
62
63
package stack
type noCopy struct{}
func (*noCopy) Lock() {}
func (*noCopy) Unlock() {}
// Element is an Element of a stack.
type Element[T any] struct {
// Next Element in the stack
next *Element[T]
// The Value stored with this element.
Value T
}
func New[T any](init ...T) *Stack[T] {
s := &Stack[T]{}
if len(init) > 0 {
elems := make([]Element[T], len(init))
for i, val := range init {
elems[i] = Element[T]{
Value: val,
}
if i < len(elems)-1 {
elems[i].next = &elems[i+1]
}
}
s.current = &elems[0]
}
return s
}
// Stack is a generic stack datastructure
type Stack[T any] struct {
noCopy noCopy
current *Element[T]
}
// Pop removes and returns the top Element from the stack
func (l *Stack[T]) Pop() *Element[T] {
this := l.current
if this != nil {
l.current = this.next
}
return this
}
// Peek returns the top Element from the stack without removing it
func (l *Stack[T]) Peek() *Element[T] {
return l.current
}
// Push adds a new item to the top of the stack
func (l *Stack[T]) Push(v T) {
l.current = &Element[T]{next: l.current, Value: v}
}
// Swap replaces the current items value
func (l *Stack[T]) Swap(v T) {
l.current.Value = v
}