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

82 lines
1.6 KiB
Go

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