In Go, implementing a generic deque (double-ended queue) allows you to efficiently add and remove elements from both ends. Below is a simple implementation using Go's support for generics introduced in Go 1.18.
package main
import "fmt"
type Deque[T any] struct {
items []T
}
func NewDeque[T any]() *Deque[T] {
return &Deque[T]{items: []T{}}
}
func (d *Deque[T]) PushFront(item T) {
d.items = append([]T{item}, d.items...)
}
func (d *Deque[T]) PushBack(item T) {
d.items = append(d.items, item)
}
func (d *Deque[T]) PopFront() (T, bool) {
if len(d.items) == 0 {
var zero T
return zero, false
}
item := d.items[0]
d.items = d.items[1:]
return item, true
}
func (d *Deque[T]) PopBack() (T, bool) {
if len(d.items) == 0 {
var zero T
return zero, false
}
item := d.items[len(d.items)-1]
d.items = d.items[:len(d.items)-1]
return item, true
}
func (d *Deque[T]) IsEmpty() bool {
return len(d.items) == 0
}
func (d *Deque[T]) Size() int {
return len(d.items)
}
func main() {
deque := NewDeque[int]()
deque.PushBack(1)
deque.PushBack(2)
deque.PushFront(0)
fmt.Println(deque.PopFront()) // Outputs: 0
fmt.Println(deque.PopBack()) // Outputs: 2
}
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?