Skip to content

Commit 39f2185

Browse files
committed
单链表实现LRU缓存
1 parent 15d26bf commit 39f2185

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/main/java/com/algorithm/study/demo/LRUCache/LRULinked.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@
1010
* @Version: 1.0
1111
*/
1212
public class LRULinked<K,V>{
13+
//缓存
1314
private final Map<K, V> cacheMap = new HashMap<>();
14-
15+
//根节点
1516
private Node<K, V> root;
1617
private int cacheSize;
1718
private int size;
@@ -29,23 +30,22 @@ public void put(K key,V value){
2930
Node<K, V> temp=root.next;
3031
if (temp==null){
3132
root=null;
32-
size--;
3333
}else{
3434
Node<K, V> current=root;
3535
while (temp.next!=null){
3636
current=temp;
3737
temp=temp.next;
3838
}
3939
current.next=null;
40-
size--;
4140
}
41+
size--;
4242
}
4343
node.next=root;
4444
root=node;
4545
size++;
4646
}
4747
public V get(K key){
48-
for (Node<K,V> node = root; node!=null; node=node.next){
48+
for (Node<K,V> node = root; node!=null&&!root.key.equals(key); node=node.next){
4949
if (node.next.key.equals(key)){
5050
Node<K, V> nodeNew=new Node<K, V>(node.next.key,node.next.value);
5151
node.next=node.next.next;
@@ -84,7 +84,7 @@ public static void main(String[] args) {
8484
linked.put("a","a");
8585
linked.put("b","b");
8686
linked.put("c","c");
87-
linked.get("a");
87+
linked.get("b");
8888
linked.put("d","d");
8989
System.out.println(linked.size);
9090
System.out.println(linked.toString());

0 commit comments

Comments
 (0)