Exemplo n.º 1
0
        public void AddCache(int key, int val)
        {
            CacheNode node = new CacheNode(key, val);

            node.Next = head.Next;
            node.Prev = head;
            head.Next = node;
            if (node.Next != null)
                node.Next.Prev = node;

            if (tail == head)
            {
                tail = head.Next;
            }

            map.Add(key, node);

            if (map.Count > maxCacheSize)
            {
                map.Remove(tail.Key);
                tail = tail.Prev;
                tail.Next = null;
            }
        }
Exemplo n.º 2
0
 public LRUCache(int size)
 {
     tail = head;
     maxCacheSize = size;
 }
Exemplo n.º 3
0
 public CacheNode()
 {
     Value = Key = 0;
     Next = Prev = null;
 }
Exemplo n.º 4
0
 public CacheNode(int key, int val)
 {
     Next = Prev = null;
     Value = val;
     Key = key;
 }
Exemplo n.º 5
0
        public CacheNode GetCache(int key)
        {
            if (map.ContainsKey(key))
            {
                CacheNode node = map[key];

                // If node is already the first one in the list, nothing need to be done
                if (node != head.Next)
                {
                    if (tail == node)
                    {
                        tail = node.Prev;
                        tail.Next = null;
                    }
                    else
                    {
                        node.Prev.Next = node.Next;
                        node.Next.Prev = node.Prev;
                    }

                    head.Next.Prev = node;
                    node.Next = head.Next;
                    node.Prev = head;
                    head.Next = node;
                }

                return node;
            }

            return null;
        }