【LeetCode】LRU Cache

设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 

package letcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 双向链表+HashMap
 * 
 * @author zeze
 *
 */
public class LRUCache {
	
	
	public static void main(String[] args) {

		/*char key = 0;
		int value = 0;
		LRUCache obj = new LRUCache(capacity);
		int param_1 = obj.get(key);
		obj.put(key, value);*/

	}

	int capacity;
	Map<Integer, Node> map = new HashMap<Integer, Node>();
	Node head = null;
	Node end = null;



	public LRUCache(int capacity) {
		this.capacity = capacity;
	}

	public int get(int key) {

		if (map.containsKey(key)) {
			Node temp = map.get(key);
			remove(temp);// 移除节点
			setHead(temp);// 将节点设置为头结点
			return temp.value;
		}
		return -1;
	}
	
	public void put(int key, int value) {
		if (map.containsKey(key)) {// 更新节点
			Node old = map.get(key);
			old.value = value;
			remove(old);
			setHead(old);
		} else {// 插入节点
			Node created = new Node(key, value);
			if (map.size() >= capacity) {
				map.remove(end.key);// HashMap中移除尾节点
				remove(end);// 链表中移除尾节点
				setHead(created);
			} else {
				setHead(created);
			}
			map.put(key, created);
		}
	}

	private void setHead(Node n) {
		n.next = head;
		n.pre = null;
		if (head != null) {
			head.pre = n;
		}
		head = n;
		if (end == null)
			end = head;

	}

	private void remove(Node n) {
		if (n.pre != null)
			n.pre.next = n.next;
		else
			head = n.next;
		if (n.next != null)
			n.next.pre = n.pre;
		else
			end = n.pre;

	}

	
}

class Node {
	int key;
	int value;
	Node pre;
	Node next;

	Node(int key, int value) {
		this.key = key;
		this.value = value;
	}
}

  

posted @ 2018-09-05 09:12  陈泽泽  阅读(359)  评论(0编辑  收藏  举报