#include <stdio.h>
#include <stdlib.h>
//双链表节点结构
typedef struct Node {
int key;
int value;
struct Node* pre;
struct Node* next;
} Node;
//LRU结构
typedef struct
{
int capacity;
struct Node* head;
struct Node* tail;
struct Node** cache;
}LRUCache;
//创建新节点
Node* createNode(int key, int value)
{
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->pre = NULL;
newNode->next = NULL;
return newNode;
}
//创建LRU缓存
LRUCache* creatLRUCache(int capacity)
{
LRUCache* cache = (LRUCache*)malloc(sizeof(LRUCache));
cache->capacity = capacity;
cache->head = createNode(0, 0);
cache->tail = createNode(0, 0);
cache->head->next = cache->tail;
cache->tail->pre = cache->head;
cache->cache = (Node**)malloc(sizeof(Node*)*100001);
for (int i = 0; i < 100001; i++)
{
cache->cache[i] = NULL;
}
return cache;
}
//删除节点
void deleteNode(Node* node)
{
node->pre->next = node->next;
node->next->pre = node->pre;
}
//插入节点到头部
void insertToHead(Node* node, Node* head)
{
node->next = head->next;
node->pre = head;
head->next = node;
node->next->pre = node;
}
int getLRUCacheValue(LRUCache* obj, int key)
{
if (obj->cache[key] != NULL)
{
Node* node = obj->cache[key];
deleteNode(node);
insertToHead(node, obj->head);
return node->value;
}
return -1;
}
void setLRUCacheValue(LRUCache* obj, int key, int value)
{
if (obj->cache[key] != NULL)
{
Node* node = obj->cache[key];
node->value = value;
deleteNode(node);
insertToHead(node, obj->head);
}
else
{
Node* newNode = createNode(key, value);
obj->cache[key] = newNode;
insertToHead(newNode, obj->head);
if(obj->capacity-- == 0)
{
Node* tail = obj->tail->pre;
deleteNode(tail);
obj->cache[tail->key] = NULL;
free(tail);
obj->capacity++;
}
}
}
//释放内存
void LRUCacheFree(LRUCache* obj)
{
for (int i = 0; i < 100001; i++)
{
if (obj->cache[i] != NULL)
{
free(obj->cache[i]);
}
}
free(obj->cache);
free(obj->head);
free(obj->tail);
free(obj);
}
int main()
{
LRUCache* obj = creatLRUCache(2);
setLRUCacheValue(obj, 1, 1);
setLRUCacheValue(obj, 2, 2);
printf("%d\n", getLRUCacheValue(obj, 1));
setLRUCacheValue(obj, 3, 3);
printf("%d\n", getLRUCacheValue(obj, 2));
setLRUCacheValue(obj, 4, 4);
printf("%d\n", getLRUCacheValue(obj, 1));
printf("%d\n", getLRUCacheValue(obj, 3));
printf("%d\n", getLRUCacheValue(obj, 4));
LRUCacheFree(obj);
system("pause");
return 0;
}
参考:https://blog.csdn.net/Conner7/article/details/136572016文章来源地址https://www.toymoban.com/news/detail-848815.html
文章来源:https://www.toymoban.com/news/detail-848815.html
到了这里,关于LRU缓存结构【C语言】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!