Skip to content

Commit 13727a7

Browse files
committed
Add TestRankAfterDel test case.
1 parent 94eafe3 commit 13727a7

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

ranklist.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,8 @@ func (sl *RankList[K, V]) Set(key K, value V) {
179179
} else {
180180
newNode.span[i] = rank[0] - rank[i] + 1
181181
if newNode.forward[i] != nil {
182-
newNode.forward[i].span[i] = newNode.span[i] + 1
182+
// 后面节点的span,被插入的节点切割了
183+
newNode.forward[i].span[i] = newNode.forward[i].span[i] - newNode.span[i] + 1
183184
}
184185
}
185186
}
@@ -242,11 +243,20 @@ func (sl *RankList[K, V]) del(key K) bool {
242243
// Update forward pointers and spans
243244
for i := 0; i < sl.level; i++ {
244245
curr = prev[i].forward[i]
246+
245247
if curr != nil && curr.data.Key == key && curr.data.Value == value {
246-
next := curr.forward[i]
247-
if next != nil {
248-
next.span[i] += curr.span[i] - 1
248+
// 如果这一层找到了删除的节点,那么将删除节点清除,并将删除节点的 span 甩给后面的节点
249+
// If the node to be deleted is found at this level, remove the node and pass its span to the next node
250+
prev[i].forward[i] = curr.forward[i]
251+
if curr.forward[i] != nil {
252+
curr.forward[i].span[i] += (curr.span[i] - 1)
249253
}
254+
255+
} else if curr != nil {
256+
// 如果没有找到节点,说明这些层级比删除的节点的层级高,这些比删除节点高的节点,span 要 -1
257+
// If the node is not found, it means these levels are higher than the level of the node to be deleted,
258+
// so the span of these higher-level nodes needs to be decremented by 1
259+
curr.span[i]--
250260
}
251261
}
252262

ranklist_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ func TestRank(t *testing.T) {
9999
{"c", 3, 3},
100100
{"d", 3, 4},
101101
{"e", 4, 5},
102+
{"f", 5, 6},
102103
}
103104

104105
for _, data := range testData {
@@ -124,6 +125,42 @@ func TestRank(t *testing.T) {
124125
}
125126
}
126127

128+
func TestRankAfterDel(t *testing.T) {
129+
sl := New[string, int]()
130+
131+
testData := []struct {
132+
key string
133+
value int
134+
rank int
135+
}{
136+
{"a", 1, 1},
137+
{"b", 2, 2},
138+
{"d", 3, 3},
139+
{"e", 4, 4},
140+
{"g", 6, 5},
141+
{"h", 7, 6},
142+
}
143+
144+
for _, data := range testData {
145+
sl.Set(data.key, data.value)
146+
}
147+
148+
sl.Set("c", 3)
149+
sl.Del("c")
150+
sl.Set("f", 5)
151+
sl.Del("f")
152+
153+
for _, data := range testData {
154+
rank, exists := sl.Rank(data.key)
155+
if !exists {
156+
t.Fatalf("Key %s should exist", data.key)
157+
}
158+
if rank != data.rank {
159+
t.Errorf("Key %s: expected rank %d, got %d", data.key, data.rank, rank)
160+
}
161+
}
162+
}
163+
127164
func TestMassiveRank(t *testing.T) {
128165
sl := New[string, int64]()
129166
for k := 0; k < 10000; k++ {

0 commit comments

Comments
 (0)