Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created June 3, 2023 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheAlchemistKE/a222e7078b983051a3a07998cda95774 to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/a222e7078b983051a3a07998cda95774 to your computer and use it in GitHub Desktop.
package main
import "fmt"
type Stack []string
// IsEmpty: check if stack is empty
func (s *Stack) IsEmpty() bool {
return len(*s) == 0
}
// Push a new value onto the stack
func (s *Stack) Push(str string) {
*s = append(*s, str) // Simply append the new value to the end of the stack
}
// Remove and return top element of stack. Return false if stack is empty.
func (s *Stack) Pop() (string, bool) {
if s.IsEmpty() {
return "", false
} else {
index := len(*s) - 1 // Get the index of the top most element.
element := (*s)[index] // Index into the slice and obtain the element.
*s = (*s)[:index] // Remove it from the stack by slicing it off.
return element, true
}
}
func main() {
var stack Stack // create a stack variable of type Stack
stack.Push("this")
stack.Push("is")
stack.Push("sparta!!")
for len(stack) > 0 {
x, y := stack.Pop()
if y == true {
fmt.Println(x)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment