-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack.go2
69 lines (53 loc) · 1.01 KB
/
stack.go2
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
package main
// vim:set ft=go:
// snip ------------------------------------------------------------------------
type Stack[T any] struct {
a []T
}
func NewStack[T any]() *Stack[T] {
return &Stack[T]{make([]T, 0)}
}
func (st *Stack[T]) Len() int {
return len(st.a)
}
func (st *Stack[T]) Empty() bool {
return st.Len() == 0
}
func (st *Stack[T]) Top() T {
return st.a[len(st.a)-1]
}
func (st *Stack[T]) Push(x T) {
st.a = append(st.a, x)
}
func (st *Stack[T]) Pop() T {
n := len(st.a) - 1
x := st.a[n]
st.a = st.a[:n]
return x
}
func (st *Stack[T]) Clear() {
st.a = st.a[:0]
}
type RTStackNode[T any] struct {
val T
next *RTStackNode[T]
}
func NewRTStack[T any]() *RTStackNode[T] {
var res *RTStackNode[T]
return res
}
func (st *RTStackNode[T]) Empty() bool {
return st == nil
}
func (st *RTStackNode[T]) Top() T {
return st.val
}
func (st *RTStackNode[T]) Push(x T) *RTStackNode[T] {
return &RTStackNode[T]{
val: x,
next: st,
}
}
func (st *RTStackNode[T]) Pop() *RTStackNode[T] {
return st.next
}