Skip to content

Instantly share code, notes, and snippets.

@Legion112
Created June 27, 2025 07:46
Show Gist options
  • Save Legion112/866b54fa82a794517f874d85494983b2 to your computer and use it in GitHub Desktop.
Save Legion112/866b54fa82a794517f874d85494983b2 to your computer and use it in GitHub Desktop.
Generic Double Linked List
package genericlist
import (
"container/list"
)
// List is a generic wrapper around container/list.List
type List[T any] struct {
l *list.List
}
// New creates a new generic list
func New[T any]() *List[T] {
return &List[T]{l: list.New()}
}
// PushFront adds a new element at the front of the list
func (gl *List[T]) PushFront(value T) *list.Element {
return gl.l.PushFront(value)
}
// PushBack adds a new element at the back of the list
func (gl *List[T]) PushBack(value T) *list.Element {
return gl.l.PushBack(value)
}
// Front returns the first element in the list
func (gl *List[T]) Front() *list.Element {
return gl.l.Front()
}
// Back returns the last element in the list
func (gl *List[T]) Back() *list.Element {
return gl.l.Back()
}
// Remove removes an element from the list
func (gl *List[T]) Remove(e *list.Element) {
gl.l.Remove(e)
}
// Len returns the length of the list
func (gl *List[T]) Len() int {
return gl.l.Len()
}
// Iterate iterates over the list and applies the provided function to each element's value
func (gl *List[T]) Iterate(f func(value T)) {
for e := gl.l.Front(); e != nil; e = e.Next() {
if val, ok := e.Value.(T); ok {
f(val)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment