scratch/algos/stack.go (view raw)
| 1 | package algos |
| 2 | |
| 3 | type SNode[T any] struct { |
| 4 | v T |
| 5 | prev *SNode[T] |
| 6 | } |
| 7 | |
| 8 | type Stack[T any] struct { |
| 9 | Len int |
| 10 | head *SNode[T] |
| 11 | } |
| 12 | |
| 13 | func (s *Stack[T]) Push(item T) { |
| 14 | node := &SNode[T]{v: item, prev: s.head} |
| 15 | s.head = node |
| 16 | s.Len++ |
| 17 | } |
| 18 | |
| 19 | func (s *Stack[T]) Peek() T { |
| 20 | return s.head.v |
| 21 | } |
| 22 | |
| 23 | func (s *Stack[T]) Pop() (val T, ok bool) { |
| 24 | if s.Len == 0 { |
| 25 | var t T |
| 26 | return t, false |
| 27 | } |
| 28 | res := s.head.v |
| 29 | s.head = s.head.prev |
| 30 | s.Len-- |
| 31 | return res, true |
| 32 | } |