Skip to content

Instantly share code, notes, and snippets.

@akosela
Created January 14, 2015 21:40
Show Gist options
  • Save akosela/9c90533f74bd162c8884 to your computer and use it in GitHub Desktop.
Save akosela/9c90533f74bd162c8884 to your computer and use it in GitHub Desktop.
// Stack in Go
package main
import "fmt"
type stack []int
func (s stack) Empty() bool { return len(s) == 0 }
func (s stack) Peek() int { return s[len(s)-1] }
func (s *stack) Put(i int) { *s = append(*s, i) }
func (s *stack) Pop() int {
d := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return d
}
func main() {
var s stack
for i := 0; i < 3; i++ {
s.Put(i)
fmt.Printf("len=%d\n", len(s))
fmt.Printf("peek=%d\n\n", s.Peek())
}
for !s.Empty() {
i := s.Pop()
fmt.Printf("len=%d\n", len(s))
fmt.Printf("pop=%d\n\n", i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment