Files

112 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-05-17 18:30:33 +08:00
// Copyright 2022 GoEdge goedge.cdn@gmail.com. All rights reserved.
2022-01-12 21:09:00 +08:00
package linkedlist
2023-12-03 11:27:47 +08:00
type List[T any] struct {
2023-10-03 21:38:45 +08:00
head *Item[T]
end *Item[T]
2022-01-12 21:09:00 +08:00
count int
}
2023-10-03 21:38:45 +08:00
func NewList[T any]() *List[T] {
return &List[T]{}
2022-01-12 21:09:00 +08:00
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) Head() *Item[T] {
2022-01-12 21:09:00 +08:00
return this.head
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) End() *Item[T] {
2022-01-12 21:09:00 +08:00
return this.end
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) Push(item *Item[T]) {
2022-01-12 21:09:00 +08:00
if item == nil {
return
}
// 如果已经在末尾了则do nothing
if this.end == item {
return
}
if item.prev != nil || item.next != nil || this.head == item {
this.Remove(item)
}
this.add(item)
}
2023-12-03 11:27:47 +08:00
func (this *List[T]) Shift() *Item[T] {
if this.head != nil {
var old = this.head
this.Remove(this.head)
return old
}
return nil
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) Remove(item *Item[T]) {
2022-01-12 21:09:00 +08:00
if item == nil {
return
}
if item.prev != nil {
item.prev.next = item.next
}
if item.next != nil {
item.next.prev = item.prev
}
if item == this.head {
this.head = item.next
}
if item == this.end {
this.end = item.prev
}
item.prev = nil
item.next = nil
this.count--
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) Len() int {
2022-01-12 21:09:00 +08:00
return this.count
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) Range(f func(item *Item[T]) (goNext bool)) {
2022-01-12 21:09:00 +08:00
for e := this.head; e != nil; e = e.next {
goNext := f(e)
if !goNext {
break
}
}
}
2023-12-03 11:27:47 +08:00
func (this *List[T]) RangeReverse(f func(item *Item[T]) (goNext bool)) {
for e := this.end; e != nil; e = e.prev {
goNext := f(e)
if !goNext {
break
}
}
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) Reset() {
2022-01-12 21:09:00 +08:00
this.head = nil
this.end = nil
}
2023-10-03 21:38:45 +08:00
func (this *List[T]) add(item *Item[T]) {
2022-01-12 21:09:00 +08:00
if item == nil {
return
}
if this.end != nil {
this.end.next = item
item.prev = this.end
item.next = nil
}
this.end = item
if this.head == nil {
this.head = item
}
this.count++
}