Skip to content

Instantly share code, notes, and snippets.

@kiambogo
Last active May 7, 2021 04:50
Show Gist options
  • Save kiambogo/55613306445b34f5380ff72a2fbe335a to your computer and use it in GitHub Desktop.
Save kiambogo/55613306445b34f5380ff72a2fbe335a to your computer and use it in GitHub Desktop.
Go Stack
package main
import "log"
type Node struct {
val int
next *Node
}
type Stack struct {
top *Node
}
func (s Stack) Peek() *Node {
return s.top
}
func (s *Stack) Pop() *Node {
if s.IsEmpty() {
return nil
}
val := s.top
s.top = s.top.next
return val
}
func (s *Stack) Push(node *Node) {
node.next = s.top
s.top = node
}
func (s Stack) IsEmpty() bool {
return s.top == nil
}
func main() {
stack := &Stack{}
assert(true, stack.IsEmpty())
assert((*Node)(nil), stack.Peek())
assert((*Node)(nil), stack.Pop())
stack.Push(&Node{val: 1})
stack.Push(&Node{val: 2})
stack.Push(&Node{val: 3})
assert(false, stack.IsEmpty())
assert(3, stack.Peek().val)
assert(3, stack.Pop().val)
assert(2, stack.Pop().val)
assert(1, stack.Pop().val)
assert(true, stack.IsEmpty())
assert((*Node)(nil), stack.Pop())
}
func assert(expected, actual interface{}) {
if expected != actual {
log.Panicf("%s != %s", expected, actual)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment