Skip to content

Instantly share code, notes, and snippets.

@zjor
Created April 8, 2025 20:57
Show Gist options
  • Save zjor/a72fbb8b5d67acea792a15b6496237ee to your computer and use it in GitHub Desktop.
Save zjor/a72fbb8b5d67acea792a15b6496237ee to your computer and use it in GitHub Desktop.
Generic Stack implementation in Go
type Node[T any] struct {
Value T
Prev *Node[T]
}
type Stack[T any] struct {
Head *Node[T]
Size int
}
func NewStack[T any]() *Stack[T] {
return &Stack[T]{
Head: nil,
Size: 0,
}
}
func (s *Stack[T]) Push(value T) {
node := Node[T]{Value: value, Prev: s.Head}
s.Head = &node
s.Size++
}
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if s.Size == 0 {
return zero, false
}
value := s.Head.Value
s.Head = s.Head.Prev
s.Size--
return value, true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment