public class LRU {
final static int MAXSIZE = 5 ;
public static void main ( String [ ] args) {
HashMap < Integer , String > cache = new HashMap < > ( ) ;
Node < Integer , String > head = new Node < > ( 0 , "0" ) ;
myPut ( cache, new Node < Integer , String > ( 1 , "a" ) , head) ;
myPut ( cache, new Node < Integer , String > ( 2 , "b" ) , head) ;
myPut ( cache, new Node < Integer , String > ( 3 , "c" ) , head) ;
myPut ( cache, new Node < Integer , String > ( 4 , "d" ) , head) ;
myPut ( cache, new Node < Integer , String > ( 5 , "e" ) , head) ;
myPut ( cache, new Node < Integer , String > ( 6 , "f" ) , head) ;
myPut ( cache, new Node < Integer , String > ( 7 , "g" ) , head) ;
System . out. println ( myGet ( cache, head, 4 ) ) ;
}
public static void myPut ( Map < Integer , String > cache , Node < Integer , String > node , Node head) {
Node p = head;
node. next = p. next;
p. next = node;
if ( cache. size ( ) >= MAXSIZE) {
for ( int i = 0 ; i < MAXSIZE ; i++ ) {
p = p. next;
}
cache. remove ( node. key) ;
p. next = null ;
}
cache. put ( node. key, node. value) ;
Node temp = head. next;
while ( temp != null ) {
System . out. print ( temp. value+ "->" ) ;
temp = temp. next;
}
System . out. println ( ) ;
}
public static String myGet ( Map < Integer , String > cache , Node head , Integer key) {
Node p = head;
String res = null ;
if ( cache. containsKey ( key) ) {
res = cache. get ( key) ;
while ( p. next. key != key) {
p = p. next;
}
Node temp = p. next;
p. next = temp. next;
temp. next = head. next;
head. next = temp;
}
Node temp = head. next;
while ( temp != null ) {
System . out. print ( temp. value+ "->" ) ;
temp = temp. next;
}
System . out. println ( ) ;
return res;
}
}
class Node < K , V > {
K key;
V value;
Node < K , V > next;
public Node ( K key, V value) {
this . key = key;
this . value = value;
this . next = null ;
}
}