/* * file name: LRUCache.h * desp: LRU缓存接口 */ #ifndef __LRUCACHE_H__ #define __LRUCACHE_H__ int LRUCacheCreate(int capacity, void **lruCache); int LRUCacheDestroy(void *lruCache); int LRUCacheSet(void *lruCache, char key, char data); char LRUCacheGet(void *lruCache, char key); void LRUCachePrint(void *lruCache); #endif
头文件描述
/* LRUCacheImpl.h 定义LRU缓存内部数据结构 */ #ifndef __LRUCACHEIMPL_H__ #define __LRUCACHEIMPL_H__ /*定义LRU缓存的缓存单元*/ typedef struct cacheEntryS { char key; char data; struct cacheEntryS *hashListPrev; /* 缓存哈希表指针,指向哈希链表的前一个元素 */ struct cacheEntryS *hashListNext; /* 缓存哈希表指针,指向哈希链表的后一个元素 */ struct cacheEntryS *lruListPrev; /* 缓存双向链表,指向双向链表的前一个元素 */ struct cacheEntryS *lruListNext; /* 缓存双向链表,指向双向链表的后一个元素 */ }cacheEntryS; typedef struct LRUCacheS { int cacheCapacity; cacheEntryS **hashMap; //缓存的hash表 cacheEntryS *lruListHead; //缓存双向链表的表头 cacheEntryS *lruListTail; //缓存双向链表表位 int lruListSize; //缓存双向链表节点个数 }LRUCacheS; #endif
相关函数介绍
/* LRUCacheImpl.c */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include"LRUCache.h" #include"LRUCacheImpl.h" static void freeList(LRUCacheS *cache); /**************************************************** *LRU缓存及缓存单位相关接口及实现 *****************************************************/ //创建一个缓存单位 static cacheEntryS *newCacheEntry(char key, char data) { cacheEntryS* entry = NULL; if (NULL == (entry = malloc(sizeof(*entry)))) { perror("malloc"); return NULL; } memset(entry, 0, sizeof(*entry)); entry->key = key; entry->data = data; return entry; } //释放一个缓存单元 static void freeCacheEntry(cacheEntryS* entry) { if (NULL == entry) { return ; } free(entry); } //创建一个LRU缓存 int LRUCacheCreate(int capacity, void **lruCache) { LRUCacheS* cache = NULL; if (NULL == (cache = malloc(sizeof(*cache)))) { perror("malloc"); return -1; } memset(cache, 0, sizeof(*cache)); cache->cacheCapacity = capacity; cache->hashMap = (cacheEntryS**)malloc(sizeof(cacheEntryS)*capacity); if (NULL == cache->hashMap) { free(cache); perror("malloc"); return -1; } memset(cache->hashMap, 0, sizeof(cacheEntryS)*capacity); *lruCache = cache; return 0; } //释放一个LRU缓存 int LRUCacheDestroy(void *lruCache) { LRUCacheS* cache = (LRUCacheS*)lruCache; if (NULL == cache) { return 0; } if (cache->hashMap) { free(cache->hashMap); } freeList(cache); free(cache); return 0; } /**************************************************** * 双向链表相关接口及实现 *****************************************************/ //从双向链表中删除指定节点 static void removeFromList(LRUCacheS *cache, cacheEntryS* entry) { //链表为空 if (cache->lruListSize == 0) { return; } if (en