LRU缓存的代码实现

#基本实现是用一个双向链表来保存节点,同时使用Hashtable来保存每个节点的映射关系 

import java.util.*;

class LRUCache {    
   
    class DListNode{
        int value;
        int key;
        DListNode pre;
        DListNode post;
    }
    
    public void addNode(DListNode node){
        
        node.pre=head;
        node.post=head.post;
        
        head.post.pre=node;
        head.post=node;
        
    }
    
    public void removeNode(DListNode node){
        DListNode pre=node.pre;
        DListNode post=node.post;
        pre.post=post;
        post.pre=pre;
    }
    
    public void moveToHead(DListNode node){
        removeNode(node);
        addNode(node);
    }
    
    public DListNode poolTail(){
        DListNode result=tail.pre;
        removeNode(result);
        return result;
        
    }
    
    private int count;
    private DListNode head;
    private DListNode tail;
    private Hashtable<Integer,DListNode> cache=new Hashtable<Integer,DListNode>();
    private int capacity;
    
    public LRUCache(int capacity) {
        this.capacity=capacity;
        this.count=0;
        head=new DListNode();
        head.pre=null;
        
        tail=new DListNode();
        tail.post=null;
        
        head.post=tail;
        tail.pre=head;
    }
    
    public int get(int key) {
        DListNode node=cache.get(key);
        if(node==null){
            return -1;
        }
        
        moveToHead(node);
        return node.value;
    }
    
    public void put(int key, int value) {
       DListNode node=cache.get(key);
       if(node==null){
           DListNode cur=new DListNode();
           cur.key=key;
           cur.value=value;
           cache.put(key,cur);
           addNode(cur);
           count++;
           
           if(count>capacity){
               DListNode last=poolTail();
               cache.remove(last.key);
               count--;
           }
       }else{
           node.value=value;
           moveToHead(node);
       }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值