From 1fd932c0ef06e5af3d793c1c0bc7d0e80a0accf1 Mon Sep 17 00:00:00 2001 From: raj_mathe Date: Fri, 5 Nov 2021 15:43:24 +0100 Subject: [PATCH] =?UTF-8?q?master=20>=20master:=20code=20go=20-=20f=C3=BCg?= =?UTF-8?q?te=20datenstruktur=20(stacks)=20hinzu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/data_structures/stacks/stacks.go | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 code/golang/internal/data_structures/stacks/stacks.go diff --git a/code/golang/internal/data_structures/stacks/stacks.go b/code/golang/internal/data_structures/stacks/stacks.go new file mode 100644 index 0000000..e990528 --- /dev/null +++ b/code/golang/internal/data_structures/stacks/stacks.go @@ -0,0 +1,72 @@ +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, ", ")) +}