---
title: "LRU Cache"
author: "KickCode"
date: "2016-02-29T10:37:04Z"
tags: []
categories: ["编程语言"]
slug: "lru-cache"
draft: false
lastmod: "2016-02-29T10:39:20Z"
id: 2279421
url: "https://kickcode.iteye.com/blog/2279421"
---

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

LRU(Least Recently Used 最近最少使用)是内存管理的一种页面置换算法，对于在内存中但又不用的数据块（内存块）叫做LRU，操作系统会根据哪些数据属于LRU而将其移出内存而腾出空间来加载另外的数据。这里采用双向链表加HashMap来实现，cache用双向链表连起来，最近访问的都放在链表的头部，经过几次访问尾部的就是不经常访问到的，如果cache已满，就把链表尾部的记录删除。代码如下：

```java

public class LRUCache {
    private int cacheSize;
    private CacheNode first = new CacheNode();
    private CacheNode last = new CacheNode();
    private HashMap<Integer, CacheNode> cache;
    
    public LRUCache(int capacity) {
        cacheSize = capacity;
        first.prev = last;
        last.next = first;
        cache = new HashMap<Integer, CacheNode>(capacity);
    }
    
    public int get(int key) {
        CacheNode node = cache.get(key);
        if(node != null) {
            moveToHead(node);
            return node.value;
        } else {
            return -1;
        }
    }
    
    public void set(int key, int value) {
        CacheNode node = null;
        if(!cache.containsKey(key)) {
            if(cache.size() == cacheSize) removeTail();
            node = new CacheNode(); 
            node.key = key;
            node.value = value;
            cache.put(key, node);
        } else {
            node = cache.get(key); 
            node.value = value;
        }
        moveToHead(node);
    }
    
    private void moveToHead(CacheNode node) {
        if(node.prev != null) {
            node.prev.next = node.next;
            node.next.prev = node.prev;
        }
        CacheNode head = first.prev;
        first.prev = node;
        node.next = first;
        node.prev = head;
        head.next = node;
    }
    
    private void removeTail() {
        CacheNode lastNode = last.next;
        last.next = last.next.next;
        last.next.prev = last;
        cache.remove(lastNode.key);
    }
}

class CacheNode {
    CacheNode prev;
    CacheNode next;
    int value;
    int key;
    
}

```