Untitled
unknown
plain_text
3 years ago
2.0 kB
9
Indexable
class DummyClass {
private class Node {
int key;
int value;
Node pre;
Node next;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
private Map<Integer, Node> map;
private int capacity;
private Node head;
private Node tail;
public DummyClass(int capacity) {
this.map = new HashMap<>();
this.capacity = capacity;
this.head = new Node(0, 0);
this.tail = new Node(0, 0);
head.pre = null;
head.next = tail;
tail.pre = head;
tail.next = null;
}
private void deleteNode(Node node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
private void insertToHead(Node node) {
Node headNext = head.next;
head.next = node;
headNext.pre = node;
node.pre = head;
node.next = headNext;
}
public int get(int key) {
if(!map.containsKey(key)) {
return -1;
}
Node node = map.get(key);
deleteNode(node);
insertToHead(node);
return node.value;
}
public void put(int key, int value) {
if(!map.containsKey(key)) {
if(map.size() == capacity) {
map.remove(tail.pre.key);
deleteNode(tail.pre);
}
Node currNode = new Node(key, value);
map.put(key, currNode);
insertToHead(currNode);
}
else {
Node currNode = map.get(key);
deleteNode(currNode);
currNode.value = value;
map.put(key, currNode);
insertToHead(currNode);
}
}
}Editor is loading...