ads1_2021/code/golang/pkg/data_structures/stacks/stacks.go

73 lines
1.4 KiB
Go

package stacks
/* ---------------------------------------------------------------- *
* IMPORTS
* ---------------------------------------------------------------- */
import (
"fmt"
"strings"
)
/* ---------------------------------------------------------------- *
* GLOBAL VARIABLES/CONSTANTS
* ---------------------------------------------------------------- */
//
/* ---------------------------------------------------------------- *
* TYPE
* ---------------------------------------------------------------- */
type StackInt struct {
values []int
}
/* ---------------------------------------------------------------- *
* METHODS stacks
* ---------------------------------------------------------------- */
func CREATE() StackInt {
return StackInt{
values: []int{},
}
}
func (S *StackInt) INIT() StackInt {
return StackInt{
values: []int{},
}
}
func (S StackInt) EMPTY() bool {
return len(S.values) == 0
}
func (S *StackInt) PUSH(x int) {
S.values = append(S.values, x)
}
func (S *StackInt) TOP() int {
if S.EMPTY() {
panic("Cannot pop from empty stack!")
}
return S.values[len(S.values)-1]
}
func (S *StackInt) POP() int {
x := S.TOP()
S.values = S.values[:(len(S.values) - 1)]
return x
}
func (S StackInt) String() string {
if len(S.values) == 0 {
return "-"
}
values := []string{}
for _, value := range S.values {
values = append(values, fmt.Sprintf("%v", value))
}
return fmt.Sprintf(strings.Join(values, ", "))
}