コード例 #1
0
        public void Add(int key, int value)
        {
            // just need to update value and move it to the top
            if (map.ContainsKey(key))
            {
                LRUNode node = map[key];
                doubleLinkedList.RemoveNode(node);
                node.Value = value;
                doubleLinkedList.AddToTop(node);
            }
            else
            {
                // if cache is full, then remove the least recently used node
                if (count == capacity)
                {
                    LRUNode lru = doubleLinkedList.RemoveLRUNode(); // remove the node
                    map.Remove(lru.Key);                            // the move the key out of the dictionary
                    count--;
                }

                // add a new node on top
                LRUNode node = new LRUNode(key, value);
                doubleLinkedList.AddToTop(node);
                map[key] = node;
                count++;
            }
        }
コード例 #2
0
        public LRUNode RemoveLRUNode()
        {
            LRUNode target = Tail.Previous;

            RemoveNode(target);
            return(target);
        }
コード例 #3
0
 public void RemoveNode(LRUNode node)
 {
     node.Previous.Next = node.Next;
     node.Next.Previous = node.Previous;
     node.Next          = null;
     node.Previous      = null;
 }
コード例 #4
0
 public void AddToTop(LRUNode node)
 {
     node.Next          = Head.Next;
     Head.Next.Previous = node;
     node.Previous      = Head;
     Head.Next          = node;
 }
コード例 #5
0
 public LRUDoubleLinkedList()
 {
     Head          = new LRUNode();
     Tail          = new LRUNode();
     Head.Next     = Tail;
     Tail.Previous = Head;
 }
コード例 #6
0
        // each time when access the node, we move it to the top
        public int Get(int key)
        {
            if (!map.ContainsKey(key))
            {
                return(-1);
            }
            LRUNode node = map[key];

            doubleLinkedList.RemoveNode(node);           // Remove node out of the list
            doubleLinkedList.AddToTop(node);             // Add back it on the top
            return(node.Value);
        }