removeNode 有错

This commit is contained in:
eson 2019-03-29 02:44:24 +08:00
parent 750ed93b74
commit 15d2f6acd3
3 changed files with 84 additions and 3 deletions

View File

@ -26,8 +26,7 @@ func (pq *PriorityQueue) Push(value interface{}) {
if pq.head == nil {
pq.head = n
return
}
if pq.queue.Compare(n, pq.head) == 1 {
} else if pq.queue.Compare(n.value, pq.head.value) == 1 {
pq.head = n
}
}
@ -40,6 +39,17 @@ func (pq *PriorityQueue) Top() (result interface{}, ok bool) {
}
func (pq *PriorityQueue) Pop() (result interface{}, ok bool) {
if pq.head != nil {
prev := getPrev(pq.head, 1)
result = pq.head.value
pq.queue.removeNode(pq.head)
if prev != nil {
pq.head = prev
} else {
pq.head = nil
}
return result, true
}
return nil, false
}

View File

@ -0,0 +1,71 @@
package pqueue
import (
"testing"
"github.com/Pallinder/go-randomdata"
"474420502.top/eson/structure/compare"
)
func TestPush(t *testing.T) {
pq := New(compare.Int)
for i := 0; i < 10; i++ {
v := randomdata.Number(0, 100)
pq.Push(v)
t.Error(v)
}
t.Error(pq.Pop())
t.Error(pq.Pop())
t.Error(pq.Pop())
t.Error(pq.Pop())
t.Error(pq.Pop())
}
func TestPop(t *testing.T) {
pq := New(compare.Int)
for i := 0; i < 10; i++ {
v := randomdata.Number(0, 100)
pq.Push(v)
t.Error(v)
}
for i := 0; i < 10; i++ {
t.Error(pq.Pop())
}
}
func BenchmarkPriorityPush(b *testing.B) {
l := loadTestData()
execCount := 5
b.N = len(l) * execCount
b.ResetTimer()
b.StartTimer()
for i := 0; i < execCount; i++ {
pq := New(compare.Int)
for _, v := range l {
pq.Push(v)
}
}
}
func BenchmarkPriorityPop(b *testing.B) {
l := loadTestData()
pq := New(compare.Int)
for _, v := range l {
pq.Push(v)
}
b.N = len(l) / 1000
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
pq.Pop()
}
}

View File

@ -889,7 +889,7 @@ func (tree *vbTree) fixSizeWithRemove(cur *tNode) {
ls, rs := getChildrenSize(cur)
factor := cur.size / 10 // or factor = 1
if rs >= ls*2+factor || ls >= rs*2+factor {
tree.fixSize(cur, ls, rs)
cur = tree.fixSize(cur, ls, rs)
}
}
cur = cur.parent