|
| 1 | +package com.algorithm.study.demo.LRUCache; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * 单链表实现LRU缓存 |
| 8 | + * @Author: liuxun |
| 9 | + * @CreateDate: 2019/1/23 下午4:03 |
| 10 | + * @Version: 1.0 |
| 11 | + */ |
| 12 | +public class LRULinked<K,V>{ |
| 13 | + private final Map<K, V> cacheMap = new HashMap<>(); |
| 14 | + |
| 15 | + private Node<K, V> root; |
| 16 | + private int cacheSize; |
| 17 | + private int size; |
| 18 | + public LRULinked(int cacheSize){ |
| 19 | + this.cacheSize=cacheSize; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * 插入头结点 |
| 24 | + * @param value |
| 25 | + */ |
| 26 | + public void put(K key,V value){ |
| 27 | + Node<K, V> node=new Node<K, V>(key,value); |
| 28 | + if (size==cacheSize){//容量满了删除尾节点 |
| 29 | + Node<K, V> temp=root.next; |
| 30 | + if (temp==null){ |
| 31 | + root=null; |
| 32 | + size--; |
| 33 | + }else{ |
| 34 | + Node<K, V> current=root; |
| 35 | + while (temp.next!=null){ |
| 36 | + current=temp; |
| 37 | + temp=temp.next; |
| 38 | + } |
| 39 | + current.next=null; |
| 40 | + size--; |
| 41 | + } |
| 42 | + } |
| 43 | + node.next=root; |
| 44 | + root=node; |
| 45 | + size++; |
| 46 | + } |
| 47 | + public V get(K key){ |
| 48 | + for (Node<K,V> node = root; node!=null; node=node.next){ |
| 49 | + if (node.next.key.equals(key)){ |
| 50 | + Node<K, V> nodeNew=new Node<K, V>(node.next.key,node.next.value); |
| 51 | + node.next=node.next.next; |
| 52 | + size--; |
| 53 | + this.put(nodeNew.key,nodeNew.value);//查找的节点放到头结点 |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + return cacheMap.get(key); |
| 58 | + } |
| 59 | + @Override |
| 60 | + public String toString(){ |
| 61 | + StringBuilder sb=new StringBuilder(); |
| 62 | + int j=0; |
| 63 | + Node<K, V> temp=root; |
| 64 | + while (j<size){ |
| 65 | + sb.append(temp.value); |
| 66 | + temp= temp.next;//找到最后一个结点 |
| 67 | + j++; |
| 68 | + } |
| 69 | + return sb.toString(); |
| 70 | + } |
| 71 | + |
| 72 | + public static class Node<K, V>{ |
| 73 | + private K key; |
| 74 | + private V value; |
| 75 | + private Node<K, V> next; |
| 76 | + public Node(K key, V value){ |
| 77 | + this.key=key; |
| 78 | + this.value=value; |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + public static void main(String[] args) { |
| 83 | + LRULinked<String,String> linked=new LRULinked<>(3); |
| 84 | + linked.put("a","a"); |
| 85 | + linked.put("b","b"); |
| 86 | + linked.put("c","c"); |
| 87 | + linked.get("a"); |
| 88 | + linked.put("d","d"); |
| 89 | + System.out.println(linked.size); |
| 90 | + System.out.println(linked.toString()); |
| 91 | + System.out.println(linked.toString()); |
| 92 | + System.out.println(linked.size); |
| 93 | + |
| 94 | + |
| 95 | + |
| 96 | + } |
| 97 | +} |
0 commit comments