s0146
This commit is contained in:
50
include/s0146_lru_cache.hpp
Normal file
50
include/s0146_lru_cache.hpp
Normal 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
|
||||
Reference in New Issue
Block a user