题目:
题解:
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); }
}