Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class LRUCache {
- final Node head = new Node();
- final Node tail = new Node();
- final Map<Integer, Node> nodeMap;
- final int capacity;
- public LRUCache(int capacity) {
- nodeMap = new HashMap<>(capacity);
- this.capacity = capacity;
- head.next = tail;
- tail.prev = head;
- }
- public int get(int key) {
- int result = -1;
- Node node = nodeMap.get(key);
- if(node != null) {
- result = node.val;
- remove(node);
- add(node);
- }
- return result;
- }
- public void put(int key, int value) {
- Node node = nodeMap.get(key);
- if(node != null) {
- remove(node);
- node.val = value;
- add(node);
- } else {
- if(nodeMap.size() == capacity) {
- nodeMap.remove(tail.prev.key);
- remove(tail.prev);
- }
- Node newNode = new Node();
- newNode.key = key;
- newNode.val = value;
- nodeMap.put(key, newNode);
- add(newNode);
- }
- }
- private void add(Node node) {
- Node headNext = head.next;
- node.next = headNext;
- headNext.prev = node;
- head.next = node;
- node.prev = head;
- }
- private void remove(Node node) {
- Node nextNode = node.next;
- Node prevNode = node.prev;
- prevNode.next = nextNode;
- nextNode.prev = prevNode;
- }
- /**
- Doubly Linked List implementation
- */
- class Node {
- int key;
- int val;
- Node next;
- Node prev;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement