Created
June 3, 2023 14:25
-
-
Save cod3smith/a222e7078b983051a3a07998cda95774 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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