1 struct Node { 2 int key, value; 3 Node(int k, int v) : key(k), value(v) {} 4 }; 5 6 class LRUCache{ 7 private: 8 int size; 9 listnlist;10 unordered_map ::iterator> nmap;11 public:12 LRUCache(int capacity) {13 size = capacity;14 }15 16 int get(int key) {17 if (nmap.find(key) != nmap.end()) {18 nlist.splice(nlist.begin(), nlist, nmap[key]);19 nmap[key] = nlist.begin();20 return nlist.begin()->value;21 }22 return -1;23 }24 25 void set(int key, int value) {26 if (nmap.find(key) == nmap.end()) {27 if (size == nlist.size()) {28 nmap.erase(nlist.back().key);29 nlist.pop_back();30 }31 nlist.push_front(Node(key, value));32 nmap[key] = nlist.begin();33 } else {34 nlist.splice(nlist.begin(), nlist, nmap[key]);35 nmap[key] = nlist.begin();36 nlist.begin()->value = value;37 }38 }39 };