MCPcopy Create free account
hub / github.com/careercup/ctci / Cache

Class Cache

java/Chapter 10/Question10_7/Cache.java:5–95  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3import java.util.HashMap;
4
5public class Cache {
6 public static int MAX_SIZE = 10;
7 public Node head;
8 public Node tail;
9 public HashMap<String, Node> map;
10 public int size = 0;
11
12 public Cache() {
13 map = new HashMap<String, Node>();
14 }
15
16 public void moveToFront(Node node) {
17 if (node == head) {
18 return;
19 }
20 removeFromLinkedList(node);
21 node.next = head;
22 if (head != null) {
23 head.prev = node;
24 }
25 head = node;
26 size++;
27
28 if (tail == null) {
29 tail = node;
30 }
31 }
32
33 public void moveToFront(String query) {
34 Node node = map.get(query);
35 moveToFront(node);
36 }
37
38 public void removeFromLinkedList(Node node) {
39 if (node == null) {
40 return;
41 }
42
43 if (node.next != null || node.prev != null) {
44 size--;
45 }
46
47 Node prev = node.prev;
48 if (prev != null) {
49 prev.next = node.next;
50 }
51
52 Node next = node.next;
53 if (next != null) {
54 next.prev = prev;
55 }
56
57 if (node == head) {
58 head = next;
59 }
60
61 if (node == tail) {
62 tail = prev;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected