예제 #1
0
 public LRUCache(int capacity)
 {
     Capacity = capacity;
     dic      = new Dictionary <int, DllNode>(Capacity);
     Head     = null;
     Tail     = null;
 }
예제 #2
0
        //Insert or Update
        public void Set(int key, int value)
        {
            DllNode n = null;

            if (dic.ContainsKey(key))
            {
                n = dic[key];
                RemoveKey(key);
            }

            n = new DllNode(key, value);

            //Add it back to the head;
            if (dic.Count == Capacity)
            {
                // Remove least recently used
                bool b = RemoveKey(Tail.Key);
                if (b)
                {
                    dic.Add(key, n);
                    AddToFront(n);
                }
            }
            else
            {
                dic.Add(key, n);
                AddToFront(n);
            }
        }
예제 #3
0
 public DllNode(int k, int v)
 {
     Key   = k;
     Value = v;
     Next  = null;
     Prev  = null;
 }
예제 #4
0
        public bool RemoveKey(int key)
        {
            if (!dic.ContainsKey(key))
            {
                return(false);
            }

            DllNode n = dic[key];

            RemoveFromLinkedList(n);

            dic.Remove(key);
            return(true);
        }
예제 #5
0
        public int Get(int key)
        {
            if (!dic.ContainsKey(key))
            {
                return(-1);
            }

            DllNode n = dic[key];

            if (n != Head)
            {
                RemoveFromLinkedList(n);
                AddToFront(n);
            }
            return(n.Value);
        }
예제 #6
0
 private void AddToFront(DllNode n)
 {
     if (n == null)
     {
         return;
     }
     if (Head == null)
     {
         Head = n;
         Tail = n;
     }
     else
     {
         Head.Prev = n;
         n.Next    = Head;
         Head      = n;
     }
 }
예제 #7
0
        private void RemoveFromLinkedList(DllNode n)
        {
            if (n == null)
            {
                return;
            }
            if (n.Prev != null)
            {
                n.Prev.Next = n.Next;
            }
            if (n.Next != null)
            {
                n.Next.Prev = n.Prev;
            }

            if (n == Tail)
            {
                Tail = n.Prev;
            }
            if (n == Head)
            {
                Head = n.Next;
            }
        }