Skip to content

Instantly share code, notes, and snippets.

@mauri870
Last active November 20, 2016 17:43
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 mauri870/71a4c6fa82d2940da1410e2eec1b2174 to your computer and use it in GitHub Desktop.
Save mauri870/71a4c6fa82d2940da1410e2eec1b2174 to your computer and use it in GitHub Desktop.
Go program representing a stack data structure. Test it https://play.golang.org/p/gBUeebGQVr
package main
import (
"fmt"
)
func main() {
// Create a new Stack
stack := NewStack()
// Push two items
stack.Push("First")
stack.Push("Second")
fmt.Println(stack.Items)
// Remove an item (the last inserted)
stack.Eject()
// Check if the stack is empty and his values
fmt.Println(stack.IsEmpty(), stack.Items)
}
func NewStack() *Stack {
return &Stack{}
}
type Stack struct{
Items []interface{}
}
func (s *Stack) Push(item interface{}) {
s.Items = append(s.Items, item)
}
func (s *Stack) Eject() interface{} {
i := len(s.Items) -1
defer func() {
s.Items = append(s.Items[:i], s.Items[i+1:]...)
}()
return s.Items[i]
}
func (s *Stack) IsEmpty() bool {
if len(s.Items) == 0 {
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment