本文主要是介绍C语言 | Leetcode C语言题解之第146题LRU缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
typedef struct {int key;int val;UT_hash_handle hh;
} LRUCache;LRUCache* cache = NULL;
int g_capacity = 0;
LRUCache** lRUCacheCreate(int capacity) {g_capacity = capacity;return &cache;
}int lRUCacheGet(LRUCache** obj, int key) {LRUCache* s;HASH_FIND_INT(*obj, &key, s);if (s) {HASH_DEL(*obj, s);HASH_ADD_INT(*obj, key, s);return s->val;}return -1;
}void lRUCachePut(LRUCache** obj, int key, int value) {LRUCache* s = NULL;HASH_FIND_INT(*obj, &key, s);if (s) {HASH_DEL(*obj, s);}s = (LRUCache*) malloc(sizeof (*s));s->key = key;HASH_ADD_INT(*obj, key, s);s->val = value;s = *obj;int capacity = HASH_COUNT(*obj);if (capacity > g_capacity) {HASH_DEL(*obj, s);free(s);}
}void lRUCacheFree(LRUCache** obj) {LRUCache *current_user, *tmp;HASH_ITER(hh, *obj, current_user, tmp) {HASH_DEL(*obj, current_user); free(current_user); }
}
这篇关于C语言 | Leetcode C语言题解之第146题LRU缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!