Last active
November 20, 2016 17:43
-
-
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
This file contains 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" | |
) | |
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