leetcode 146. LRU Cache 链表操作与缓存处理



public class LRUCache {
    class DlinkedNote{
    	int key;
    	int value;
    	DlinkedNote pre;
    	DlinkedNote post;
    	DlinkedNote(){}
    	DlinkedNote(int key, int value){
    		this.key = key;
    		this.value = value;
    	}
    }
	
    HashMap<Integer, DlinkedNote> cache = new HashMap<Integer, DlinkedNote>();
    int capacity;
    DlinkedNote head;
    DlinkedNote tail;
    
    
    public DlinkedNote poptail(){
    	DlinkedNote res = tail.pre;
    	removenode(res);
    	return res;
    }
    
    public void movetohead(DlinkedNote node){
		removenode(node);
		addnode(node);
	}

	public void removenode(DlinkedNote node){
		DlinkedNote pre = node.pre;
		DlinkedNote post = node.post;
		pre.post = post;
		post.pre = pre;
	}
	
	/** always add at the head of link*/
	public void addnode(DlinkedNote node){
		DlinkedNote cur_first = this.head.post;
		cur_first.pre = node;
		node.post = cur_first;
		node.pre = this.head;
		this.head.post = node;
	}
	
    public LRUCache(int capacity) {
		DlinkedNote head = new DlinkedNote();
		DlinkedNote tail = new DlinkedNote();
		head.post = tail;
		tail.pre = head;
		this.head = head;
		this.tail = tail;
		this.capacity = capacity;
//		this.count = 0;
    }
	
    public int get(int key) {
    	DlinkedNote res = cache.get(key);
    	if(res==null){
    		return -1; 
    	}
    	movetohead(res);
    	return res.value;
    }
    
    public void put(int key, int value) {
    	DlinkedNote node = cache.get(key);
    	int count = cache.size();
    	if(node==null){
    		DlinkedNote new_node = new DlinkedNote(key, value); 
    		this.cache.put(key, new_node);
    		addnode(new_node);
    		count++;
//    		while(count>this.capacity)
    		if(count>this.capacity){
    			DlinkedNote last = this.poptail();
    			cache.remove(last.key);
    		}
    	}else{
    		if(node.value!=value){
    			node.value = value;
    		}
    		movetohead(node);
    	}
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值