Created
April 8, 2025 20:57
-
-
Save zjor/a72fbb8b5d67acea792a15b6496237ee to your computer and use it in GitHub Desktop.
Generic Stack implementation in Go
This file contains hidden or 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
| 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