Skip to content

Instantly share code, notes, and snippets.

@maxclav
Created July 24, 2023 17:10
Show Gist options
  • Save maxclav/f80b804a134c4fd9dd37edfda0713759 to your computer and use it in GitHub Desktop.
Save maxclav/f80b804a134c4fd9dd37edfda0713759 to your computer and use it in GitHub Desktop.
Stack Data Structure with generics in Go (GoLang).
package stack
// Stack represents a basic stack data structure.
type Stack[T any] struct {
items []T
}
// Push adds an item to the top of the stack.
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
// Pop removes and returns the item from the top of the stack.
// It also returns a boolean value indicating whether the stack is empty.
func (s *Stack[T]) Pop() (T, bool) {
if len(s.items) == 0 {
var nilT T
return nilT, false
}
index := len(s.items) - 1
item := s.items[index]
s.items = s.items[:index]
return item, true
}
// IsEmpty checks if the stack is empty.
func (s *Stack[T]) IsEmpty() bool {
return len(s.items) == 0
}
// Size returns the number of elements in the stack.
func (s *Stack[T]) Size() int {
return len(s.items)
}
// Top returns the item at the top of the stack without removing it.
func (s *Stack[T]) Top() (T, bool) {
if len(s.items) == 0 {
var nilT T
return nilT, false
}
return s.items[len(s.items)-1], true
}
@maxclav
Copy link
Author

maxclav commented Jul 24, 2023

template-stack

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment