Created
July 24, 2023 17:10
-
-
Save maxclav/f80b804a134c4fd9dd37edfda0713759 to your computer and use it in GitHub Desktop.
Stack Data Structure with generics in Go (GoLang).
This file contains 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
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 | |
} |
Author
maxclav
commented
Jul 24, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment