Created
June 27, 2025 07:46
-
-
Save Legion112/866b54fa82a794517f874d85494983b2 to your computer and use it in GitHub Desktop.
Generic Double Linked List
This file contains hidden or 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 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