Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e319ebf

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 4d28c1b commit e319ebf

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

‎460_lfu_cache/lfu_cache.c‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,10 @@ static FreqAVLNode *avl_tree_insert(FreqAVLTree *tree, int freq)
197197
parent = *rover;
198198
if (freq < (*rover)->freq) {
199199
rover = &((*rover)->children[0]);
200-
} else {
200+
} else if (freq> (*rover)->freq) {
201201
rover = &((*rover)->children[1]);
202+
} else {
203+
return *rover;
202204
}
203205
}
204206

@@ -312,18 +314,17 @@ static void avl_tree_destory(FreqAVLTree *tree)
312314

313315
static void freq_incr(FreqAVLTree* tree, LFUNode *lfu, int key)
314316
{
317+
/* New frequency */
315318
list_del(&lfu->dlink);
319+
int freq = ++lfu->freq;
320+
FreqAVLNode *node = avl_tree_insert(tree, freq);
316321
if (list_empty(&lfu->node->dhead)) {
322+
if (lfu->node == tree->min_freq_node) {
323+
tree->min_freq_node = node;
324+
}
317325
/* we must erase the empty node to rearrange the AVL tree */
318326
avl_node_erase(tree, lfu->node);
319327
}
320-
321-
/* New frequency */
322-
int freq = ++lfu->freq;
323-
FreqAVLNode *node = avl_tree_insert(tree, freq);
324-
if (lfu->node == tree->min_freq_node) {
325-
tree->min_freq_node = node;
326-
}
327328
lfu->node = node;
328329
list_add(&lfu->dlink, &lfu->node->dhead);
329330
}
@@ -379,10 +380,7 @@ void lFUCachePut(LFUCache* obj, int key, int value)
379380
lfu = list_last_entry(&node->dhead, LFUNode, dlink);
380381
list_del(&lfu->dlink);
381382
list_del(&lfu->key_link);
382-
if (list_empty(&node->dhead)) {
383-
/* we must erase the empty node to rearrange the AVL tree */
384-
avl_node_erase(obj->tree, node);
385-
}
383+
/* NOTE: we DO NOT need to erase the empty AVL node since the min freq node would be update immediately */
386384
} else {
387385
/* new LFU */
388386
obj->size++;
@@ -428,7 +426,7 @@ void lFUCacheFree(LFUCache* obj)
428426
int main(void)
429427
{
430428
LFUCache* obj = lFUCacheCreate(2);
431-
#if 0
429+
#if 1
432430
lFUCachePut(obj, 1, 1);
433431
printf("Put 1 1\n");
434432
lFUCachePut(obj, 2, 2);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /