Skip to content

Instantly share code, notes, and snippets.

@maksadbek
Created April 10, 2020 18:37
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 maksadbek/0b50a34d60cb9b447a1fd8d20137f96f to your computer and use it in GitHub Desktop.
Save maksadbek/0b50a34d60cb9b447a1fd8d20137f96f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
type item struct {
value interface{} //value as interface type to hold any data type
next *item
}
type Stack struct {
top *item
size int
}
func (stack *Stack) Len() int {
return stack.size
}
func (stack *Stack) Push(value interface{}) {
stack.top = &item{
value: value,
next: stack.top,
}
stack.size++
}
func (stack *Stack) Pop() (value interface{}) {
if stack.Len() > 0 {
value = stack.top.value
stack.top = stack.top.next
stack.size--
return
}
return nil
}
func main() {
stack := new(Stack)
// Push different data type to the stack
stack.Push(1)
stack.Push("Welcome")
stack.Push(4.0)
// Pop until stack is empty
for stack.Len() > 0 {
fmt.Println(stack.Pop())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment