Last active
December 29, 2015 02:39
-
-
Save Koitaro/7602339 to your computer and use it in GitHub Desktop.
Stack package for Go language.
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" | |
"stack" | |
) | |
func main() { | |
s := stack.New() | |
for i := 1; i <= 5; i++ { | |
s.Push(i) | |
} | |
for s.IsNotEmpty() { | |
n := s.Pop().(int) | |
fmt.Println(n+100) | |
} | |
} |
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 stack | |
type stack struct { | |
element interface{} | |
tail *stack | |
} | |
func New() (s *stack) { | |
s = new(stack) | |
return | |
} | |
func (s *stack) Push(x interface{}) { | |
t := new(stack) | |
t.element = (*s).element | |
t.tail = (*s).tail | |
s.element = x | |
s.tail = t | |
} | |
func (s *stack) Pop() (e interface{}) { | |
if e = (*s).element; e != nil { | |
s.element = s.tail.element | |
s.tail = s.tail.tail | |
} | |
return | |
} | |
func (s *stack) IsEmpty() bool { | |
return (*s).element == nil | |
} | |
func (s *stack) IsNotEmpty() bool { | |
return (*s).element != nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment