This problem should be seen a lot, write a record.
To implement this function analysis:
(1) O (1) Time to complete the search, there is no choice except hash.
(2) LRU least recently used algorithms, in order to facilitate the elimination of data. You need to put the data that is not accessed until you have recently accessed it.
It can be realized by two-way linked list. (Typically, the doubly linked list reads, the insertion time complexity is O (n), but if you know the insertion position, you can implement an O (1) implementation.) )
Implementation: hash key corresponding to the data in the doubly linked list position, you can complete the function.
Specific code:
1#include <iostream>2#include <list>//std::list bidirectional linked list implementation3#include <map>4 5 Const intMax_value_len = +;6 Const intMax_element_num =3;7 8 structcachenode{9 intkey;Ten intLen; One CharData[max_value_len]; A }; - - classlru{ the Public: - //default of 10 original -LRU (intMax_num =max_element_num); -~LRU (); + - //Data Acquisition + BOOL Get(Const intKeyChar*data,int&len); A at //New Data - BOOL Set(Const intKeyConst Char* Data,Const intlen); - - //Print Data - voidprint_list (); - Private: in - //link to update nodes to //after accessing the element, you need to place the element in the list header + intUpdate_node_link (Const intkey); - the int_max_num; *Std::list<cachenode*>_list; $std::map<int, std::list<cachenode*>::iterator>_map;Panax Notoginseng};
Algorithm: Implement LRU cache, read, write O (1) implementation