s0146
All checks were successful
ci/woodpecker/push/deploy Pipeline was successful
ci/woodpecker/push/test Pipeline was successful

This commit is contained in:
2023-03-18 08:40:30 +08:00
parent a99d75b44c
commit bef47e10bf
5 changed files with 270 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
#ifndef S0146_LRU_CACHE_HPP
#define S0146_LRU_CACHE_HPP
#include <cstdlib>
#include <unordered_map>
class LRUCache {
public:
/**
* @brief Least Recently Used Cache
*
* 这是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰
*
* @param capacity 容量,这是一个正整数
*/
LRUCache(int capacity);
/**
* @brief 读取数据
*
* @param key 数据对应的键值
* @return 数据的值
*/
int get(int key);
/**
* @brief 放入对应的数据
*
* @param key 数据对应的键值
* @param value 数据对应的值
*/
void put(int key, int value);
private:
struct CacheNode {
int key;
int value;
CacheNode *next;
CacheNode *prev;
CacheNode(int key, int value)
: key(key), value(value), next(nullptr), prev(nullptr){};
CacheNode(int key, int value, CacheNode *next, CacheNode *prev)
: key(key), value(value), next(next), prev(prev){};
};
CacheNode *head;
CacheNode *tail;
int capacity;
std::unordered_map<int, CacheNode *> map; // 键值是 key值是该节点的指针
void moveToHead(CacheNode *node); // 将节点移动到头部
};
#endif