-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.java
142 lines (129 loc) · 2.16 KB
/
LRUCache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class LRUCache {
class Node {
int key;
int value;
Node prev;
Node next;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
HashMap<Integer, Node> m;
Node head, tail;
int capacity;
public LRUCache(int capacity) {
m = new HashMap<Integer, Node>();
head = tail = null;
this.capacity = capacity;
}
public int get(int key) {
Node x = m.get(key);
if (x == null)
return -1;
else {
if (x == head)
return x.value;
else if (x == tail) {
tail = tail.prev;;
tail.next = null;
x.next = head;
head.prev =x;
head = x;
return x.value;
} else {
x.prev.next = x.next;
x.next.prev = x.prev;
x.prev = null;
x.next = head;
head.prev =x;
head = x;
return x.value;
}
}
}
public void set(int key, int value) {
if(head==null)
{
Node a = new Node(key,value);
head = tail = a;
m.put(key, a);
return;
}
if(m.get(key)==null)
{
Node a = new Node(key,value);
if(m.size()==capacity)
{
int s = tail.key;
tail.prev.next = tail.next;
tail = tail.prev;
m.remove(s);
m.put(key, a);
a.next = head;
head.prev = a;
head = a;
}
else
{
a.next = head;
head.prev = a;
head = a;
m.put(key, a);
}
}
else
{
Node a = m.get(key);
a.value = value;
if(a==head)
{
m.put(key,a);
return;
}
if(a==tail)
{
tail=tail.prev;
tail.next = null;
a.prev = null;
a.next = head;
head.prev = a;
head = a;
m.put(key, a);
return;
}
a.prev.next = a.next;
a.next.prev = a.prev;
a.prev= null;
a.next = head;
head.prev = a;
head = a;
}
}
public void printList()
{
Node temp = head;
while(temp!=null)
{
System.out.print("("+temp.key+","+temp.value+")"+"----");
temp = temp.next;
}
System.out.println("\n");
}
public static void main(String[] args) {
LRUCache p = new LRUCache(3);
p.set(1, 10);
p.set(2, 20);
p.set(3, 30);
p.get(1);
p.printList();
p.set(1, 100);
p.set(2, 45);
p.printList();
p.set(100, 5000);
p.printList();
}
}