优化链表相关代码

This commit is contained in:
刘祥超
2023-12-03 11:27:47 +08:00
parent 981c063eff
commit 0c097498bb
2 changed files with 62 additions and 1 deletions

View File

@@ -2,7 +2,7 @@
package linkedlist
type List[T any] struct {
type List[T any] struct {
head *Item[T]
end *Item[T]
count int
@@ -36,6 +36,15 @@ func (this *List[T]) Push(item *Item[T]) {
this.add(item)
}
func (this *List[T]) Shift() *Item[T] {
if this.head != nil {
var old = this.head
this.Remove(this.head)
return old
}
return nil
}
func (this *List[T]) Remove(item *Item[T]) {
if item == nil {
return
@@ -71,6 +80,15 @@ func (this *List[T]) Range(f func(item *Item[T]) (goNext bool)) {
}
}
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
}
}
}
func (this *List[T]) Reset() {
this.head = nil
this.end = nil