手写一个LRU缓存机制算法

使用HashMap+链表

import java.util.HashMap;

/*
  * 链表          存key value
  * hashmap   存key node
 */
public class leetcode146_LRU缓存机制 {
	

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

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

	public HashMap<Integer, Node> map;
	public Node head;
	public Node tail;
	public int capacity;

	public leetcode146_LRU缓存机制(int capacity) {
		map = new HashMap<>();
		this.capacity = capacity;
	}

	public int get(int key) {
		Node node = map.get(key);
		if (node != null) {
			remove(node);
			add(node);
			return node.value;
		}
		return -1;

	}

	// 添加到最后
	private void add(Node node) {
		Node t = tail; // 取它的尾巴
		tail = node;
		// 判断之前是否有元素
		if (t == null) {
			head = node;
		} else {
			t.next = node;
			node.pre = t;
			node.next = null;
		}
		capacity--;
	}

	// 删除
	private void remove(Node node) {
		Node pre = node.pre;
		Node next = node.next;
		if (pre == null) {
			head = next;
		} else {
			pre.next = next;
		}
		if (next == null) {
			tail = pre;
		} else {
			next.pre = pre;
		}
		capacity++;
	}

	public void put(int key, int value) {

		if (map.containsKey(key)) { // 已经存在
			Node node = map.get(key);
			node.value = value; // 更新
			remove(node);
			add(node); // 放到最后
		} else {// 不存在的情况
			Node node = new Node(key, value);

			map.put(key, node);
			add(node);
		}

		if (capacity < 0) {
			Node temp = head;
			remove(head);
			map.remove(temp.key);
		}

	}

    public static void main(String[] args) {
		leetcode146_LRU缓存机制 lru = new leetcode146_LRU缓存机制(2);
		lru.put(2, 5);
		lru.put(1, 3);
		lru.put(4, 6);
		System.out.println(lru.get(2));
		System.out.println(lru.get(1));
	}
}