58 lines
769 B
Go
58 lines
769 B
Go
package tools
|
|
|
|
type Node[T any] struct {
|
|
value T
|
|
before *Node[T]
|
|
after *Node[T]
|
|
}
|
|
|
|
type List[T any] struct {
|
|
front *Node[T]
|
|
back *Node[T]
|
|
size uint
|
|
}
|
|
|
|
func New[T any]() List[T] {
|
|
return List[T]{nil, nil, 0}
|
|
}
|
|
|
|
func (l *List[T]) PushFront(t T) {
|
|
item := &Node[T]{t, nil, nil}
|
|
|
|
if l.back == nil {
|
|
l.back = item
|
|
}
|
|
|
|
if front := l.front; front != nil {
|
|
front.before, item.after = item, front
|
|
}
|
|
|
|
l.size++
|
|
l.front = item
|
|
}
|
|
|
|
func (l *List[T]) PopBack() (result T, good bool) {
|
|
if l.back == nil {
|
|
return
|
|
}
|
|
|
|
result = l.back.value
|
|
good = true
|
|
|
|
if l.front == l.back {
|
|
l.front = nil
|
|
}
|
|
|
|
if before := l.back.before; before != nil {
|
|
before.after = nil
|
|
}
|
|
|
|
l.size--
|
|
l.back = l.back.before
|
|
return
|
|
}
|
|
|
|
func (l *List[T]) Size() uint {
|
|
return l.size
|
|
}
|