diff --git a/hello.go b/hello.go index ff3c9b5..d36616d 100644 --- a/hello.go +++ b/hello.go @@ -1,7 +1,17 @@ package main -import "fmt" +import( + "../src/lib/" + "fmt" +) func main() { - fmt.Printf("Hello, World") + var s collection.Stack + s.Push("world") + s.Push("hello, ") + for s.Size() > 0 { + fmt.Print(s.Pop()) + } + fmt.Println() + // Output: hello, world } diff --git a/helloStack.go b/helloStack.go new file mode 100644 index 0000000..bfef3fd --- /dev/null +++ b/helloStack.go @@ -0,0 +1,17 @@ +package collection_test + +import ( + collection "." + "fmt" +) + +func Example() { + var s collection.Stack + s.Push("world") + s.Push("hello, ") + for s.Size() > 0 { + fmt.Print(s.Pop()) + } + fmt.Println() + // Output: hello, world +} diff --git a/lib/stack.go b/lib/stack.go new file mode 100644 index 0000000..0c37828 --- /dev/null +++ b/lib/stack.go @@ -0,0 +1,27 @@ +// Package collection implements a generic stack. +package collection + +// The zero value for Stack is an empty stack ready to use. +type Stack struct { + data []interface{} +} + +// Push adds x to the top of the stack. +func (s *Stack) Push(x interface{}) { + s.data = append(s.data, x) +} + +// Pop removes and returns the top element of the stack. +// It’s a run-time error to call Pop on an empty stack. +func (s *Stack) Pop() interface{} { + i := len(s.data) - 1 + res := s.data[i] + s.data[i] = nil // to avoid memory leak + s.data = s.data[:i] + return res +} + +// Size returns the number of elements in the stack. +func (s *Stack) Size() int { + return len(s.data) +}