A stack is a data structure that follows the Last In First Out (LIFO) principle. In Go, you can implement a stack using a slice. Below is a simple example of how to create and manage a stack in Go.
package main
import "fmt"
// Stack represents a stack data structure
type Stack struct {
items []interface{}
}
// Push adds an item to the top of the stack
func (s *Stack) Push(item interface{}) {
s.items = append(s.items, item)
}
// Pop removes and returns the item from the top of the stack
func (s *Stack) Pop() interface{} {
if len(s.items) == 0 {
return nil
}
// Get the last item
lastIndex := len(s.items) - 1
item := s.items[lastIndex]
// Remove the last item
s.items = s.items[:lastIndex]
return item
}
// Peek returns the top item without removing it from the stack
func (s *Stack) Peek() interface{} {
if len(s.items) == 0 {
return nil
}
return s.items[len(s.items)-1]
}
// IsEmpty checks if the stack is empty
func (s *Stack) IsEmpty() bool {
return len(s.items) == 0
}
func main() {
stack := Stack{}
stack.Push(1)
stack.Push(2)
stack.Push(3)
fmt.Println(stack.Pop()) // Outputs: 3
fmt.Println(stack.Peek()) // Outputs: 2
fmt.Println(stack.IsEmpty()) // Outputs: false
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?