class LRUCache{
struct Node{
int value;
int key;
Node* next;
Node* prev;
Node(int k, int val):prev(NULL),next(NULL),key(k),value(val){};
Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};
};
int cap;
unordered_map<int,Node*> mmap;
Node* head;
Node* tail;
public:
LRUCache(int capacity) {
cap = capacity;
head=NULL;
tail=NULL;
mmap.clear();
}
int get(int key) {
if(mmap.count(key)){
DragKeyNode(mmap[key]);
return mmap[key]->value;
}
else return -1;
}
void set(int key, int value) {
if(mmap.count(key)){
mmap[key]->value=value;
DragKeyNode(mmap[key]);
}
else{
Node *insertp=new Node(key,value);
mmap.insert(make_pair(key,insertp));
if(mmap.size()<=cap){
attach(insertp);
}
else{
detach();
attach(insertp);
}
}
}
void DragKeyNode(Node* KeyNode){
if(head==KeyNode){
return;
}
else{
Node* prev = KeyNode->prev;
Node* next = KeyNode->next;
prev->next=next;
if(!next){
prev->next=NULL;
tail=prev;
}
else{
next->prev=prev;
}
KeyNode->prev=NULL;
KeyNode->next=NULL;
}
attach(KeyNode);
}
void attach(Node *p){
if(!head||!tail){
head=p;
tail=p;
}
else{
p->next=head;
head->prev=p;
head=p;
}
}
void detach(){
if(!head||!tail)return;
else{
int keydelete=tail->key;
mmap.erase(keydelete);
Node* p=tail->prev;
tail->prev=NULL;
if(p){
p->next=NULL;
tail=p;
}
else{
head=NULL;
tail=NULL;
}
}
}
};
No comments:
Post a Comment