// package stack provides a generic first-in / first-out stack. package stack // stack interface type Stack[V any] interface { Depth() int Push(V) Pop() V Peek(int) V Replace(int, V) } // simple slice implementation type stack[V any] struct { tos int data []V } func NewStack[V any]() *stack[V] { return &stack[V]{ tos: -1, data: make([]V, 0, 5), } } func (st *stack[V]) Depth() int { return st.tos + 1 } func (st *stack[V]) Push(v V) { st.tos += 1 if st.tos >= len(st.data) { st.data = append(st.data, v) } else { st.data[st.tos] = v } } func (st *stack[V]) Pop() V { v := st.data[st.tos] st.tos -= 1 return v } func (st *stack[V]) Peek(i int) V { return st.data[st.tos-i] } func (st *stack[V]) Replace(i int, v V) { st.data[st.tos-i] = v }