-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d7a2d33
commit b378842
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
class LRUCache { | ||
public: | ||
class node { | ||
public: | ||
int key; | ||
int val; | ||
node * next; | ||
node * prev; | ||
node(int _key, int _val) { | ||
key = _key; | ||
val = _val; | ||
} | ||
}; | ||
|
||
node * head = new node(-1, -1); | ||
node * tail = new node(-1, -1); | ||
|
||
int cap; | ||
unordered_map < int, node * > m; | ||
|
||
LRUCache(int capacity) { | ||
cap = capacity; | ||
head -> next = tail; | ||
tail -> prev = head; | ||
} | ||
|
||
void addnode(node * newnode) { | ||
node * temp = head -> next; | ||
newnode -> next = temp; | ||
newnode -> prev = head; | ||
head -> next = newnode; | ||
temp -> prev = newnode; | ||
} | ||
|
||
void deletenode(node * delnode) { | ||
node * delprev = delnode -> prev; | ||
node * delnext = delnode -> next; | ||
delprev -> next = delnext; | ||
delnext -> prev = delprev; | ||
} | ||
|
||
int get(int key_) { | ||
if (m.find(key_) != m.end()) { | ||
node * resnode = m[key_]; | ||
int res = resnode -> val; | ||
m.erase(key_); | ||
deletenode(resnode); | ||
addnode(resnode); | ||
m[key_] = head -> next; | ||
return res; | ||
} | ||
|
||
return -1; | ||
} | ||
|
||
void put(int key_, int value) { | ||
if (m.find(key_) != m.end()) { | ||
node * existingnode = m[key_]; | ||
m.erase(key_); | ||
deletenode(existingnode); | ||
} | ||
if (m.size() == cap) { | ||
m.erase(tail -> prev -> key); | ||
deletenode(tail -> prev); | ||
} | ||
|
||
addnode(new node(key_, value)); | ||
m[key_] = head -> next; | ||
} | ||
}; |