码迷,mamicode.com
首页 > 系统相关 > 详细

LRU cache.

时间:2014-12-06 11:31:27      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:interview

See http://blog.csdn.net/hexinuaa/article/details/6630384

Node<T>
{
 T data;
 Node<T> next;
 Node<T> pre;
}

Node<T> swapToHead(Node<T> head, Node<T> n)
{
  if (n == head)
    return n;
    
  Node<T> temp = n.next;
  n.next = temp;
  if (temp != null) temp.pre = n.pre;
  n.pre = null;
  n.next = head;
  return n;
}


class LRU<K, T>
{
  private Map<K, Node<T>> map;
  private Node<T> head;
  private Node<T> tail;
  int size;
  
  T search(K key)
  {
    Node<T> n = map.get(key);
    if (n != null)
    {
      head = swapToHead(head, n);
      return head.data;
    }
    else
    {
      T = getOutFromCache(K);
      Node newNode = new Node(T);
      newNode.next = head;
      head = newNode;
      if (size == MAX_SIZE)
      {
        Node newTail = tail.pre;
        newTail.next = null;
        tail.pre = null;
        tail = null;
        tail = newTail;
      }
      else
      {
        size++;
      }
    }
    
    return T;
  }
}


LRU cache.

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1586975

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!