2
// Declare Node class for Doubly Linked List4
int key, value; // to store key and value5
Node next, prev; // Next and Previous Pointers13
Node head = new Node(-1, -1); // Default values14
Node tail = new Node(-1, -1);15
Map<Integer, Node> mp; // to store key and Node18
public LRUCache(int capacity) {19
// initializing in constructor23
mp = new HashMap<Integer, Node>();26
public int get(int key) {27
// if map contains the specific key28
if (mp.containsKey(key)) {29
Node existing = mp.get(key);31
ins(existing); // reinserting to keep key after the head pointer and to update LRU list32
return existing.value;38
public void put(int key, int value) {39
// if map contains the key40
if (mp.containsKey(key)) {41
Node existing = mp.get(key);42
// remove from the map and delete from the LRU list46
// if map size is equal to spcified capacity of the LRU list47
if (mp.size() == cap) {48
// remove from the map and delete from the LRU list49
mp.remove(tail.prev.key);52
Node newNode = new Node(key, value);54
mp.put(key, head.next);57
public void ins(Node newNode) {58
// Insert always after the head of the linkedList59
Node temp = head.next;66
public void del(Node newNode) {67
// Remove the specified node using previous and next pointers68
Node pr = newNode.prev;69
Node nx = newNode.next;