53 lines
782 B
Go
53 lines
782 B
Go
package beryl
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
)
|
|
|
|
// Generic stack
|
|
// One should implement better constraints
|
|
type stack[V any] []V
|
|
|
|
func (s *stack[V]) Push(v V) int {
|
|
*s = append(*s, v)
|
|
return len(*s)
|
|
}
|
|
func (s *stack[V]) Last() V {
|
|
l := len(*s)
|
|
|
|
// Upto the developer to handle an empty stack
|
|
if l == 0 {
|
|
log.Fatal("Empty Stack")
|
|
}
|
|
|
|
last := (*s)[l-1]
|
|
return last
|
|
}
|
|
|
|
func (s *stack[V]) SecondToLast() V {
|
|
l := len(*s)
|
|
|
|
// Upto the developer to handle an empty stack
|
|
if l <= 1 {
|
|
return s.Last()
|
|
}
|
|
|
|
last := (*s)[l-2]
|
|
return last
|
|
}
|
|
|
|
func (s *stack[V]) Pop() V {
|
|
removed := (*s).Last()
|
|
*s = (*s)[:len(*s)-1]
|
|
|
|
return removed
|
|
}
|
|
|
|
// Pointer not needed because read-only operation
|
|
func (s stack[V]) Values() {
|
|
for i := len(s) - 1; i >= 0; i-- {
|
|
fmt.Printf("%v ", s[i])
|
|
}
|
|
}
|