优化list——head

This commit is contained in:
aozhiwei 2023-09-14 22:25:58 +08:00
parent fe65489de2
commit 37aba94237

View File

@ -8,6 +8,9 @@ type ListHead struct {
data interface{} data interface{}
} }
var dummyData = &struct {
}{}
func (this *ListHead) Init(data interface{}) { func (this *ListHead) Init(data interface{}) {
this.next = this this.next = this
this.prev = this this.prev = this
@ -44,7 +47,12 @@ func (this *ListHead) AddHead(pnew *ListHead) {
} }
func (this *ListHead) FirstEntry() interface{} { func (this *ListHead) FirstEntry() interface{} {
return this.next.data for pos := this.next; pos != this; pos = pos.next {
if pos.data != dummyData {
return pos.data
}
}
return nil
} }
func (this *ListHead) Replace(pnew *ListHead) { func (this *ListHead) Replace(pnew *ListHead) {
@ -61,7 +69,18 @@ func (this *ListHead) ReplaceInit(pnew *ListHead) {
} }
func (this *ListHead) Empty() bool { func (this *ListHead) Empty() bool {
return this.next == this if this.next == this {
return true
}
if this.next.data != dummyData {
return false
}
for pos := this.next; pos != this; pos = pos.next {
if pos.data != dummyData {
return false
}
}
return true
} }
func (this *ListHead) DelInit() { func (this *ListHead) DelInit() {
@ -70,13 +89,9 @@ func (this *ListHead) DelInit() {
this.prev = this this.prev = this
} }
func (this *ListHead) Next() *ListHead {
return this.next
}
func (this *ListHead) Size() int32 { func (this *ListHead) Size() int32 {
num := int32(0) num := int32(0)
this.ForEach_r( this.ForEach(
func (data interface{}) bool { func (data interface{}) bool {
num++ num++
return true return true
@ -84,37 +99,27 @@ func (this *ListHead) Size() int32 {
return num return num
} }
func (this *ListHead) ForEachFrom(from *ListHead,
cb ListHead_Foreach_Func) {
for pos := from; pos != this; pos = pos.next {
if !cb(pos.data) {
break
}
}
}
func (this *ListHead) ForEach(cb ListHead_Foreach_Func) { func (this *ListHead) ForEach(cb ListHead_Foreach_Func) {
for pos := this.next; pos != this; pos = pos.next { cursor := ListHead{}
if !cb(pos.data) { cursor.data = dummyData
this.AddHead(&cursor)
defer cursor.Del()
for ; cursor.next != this; {
oldN := cursor.next
if cursor.next.data != dummyData && !cb(cursor.next.data) {
break break
} }
} if cursor.next == oldN {
} cursor.next = oldN.next
oldN.next.prev = &cursor
func (this *ListHead) ForEach_r(cb ListHead_Foreach_Func) { oldN.prev = cursor.prev
for pos := this.prev; pos != this; pos = pos.prev { cursor.prev.next = oldN
if !cb(pos.data) { oldN.next = &cursor
break cursor.prev = oldN
} }
} }
} }
func MakeListHead () *ListHead{
l := new(ListHead)
l.Init(nil)
return l
}
func NewListHead () *ListHead{ func NewListHead () *ListHead{
l := new(ListHead) l := new(ListHead)
l.Init(nil) l.Init(nil)