Example #1
0
        private DLinkedNode PopTail()
        {
            DLinkedNode res = tail.Prev;

            RemoveNode(res);
            return(res);
        }
Example #2
0
        public void Put(int key, int value)
        {
            DLinkedNode node = cache.ContainsKey(key) ? cache[key] : null;

            if (node == null)
            {
                var newNode = new DLinkedNode
                {
                    Key   = key,
                    Value = value
                };

                cache.Add(key, newNode);
                AddNode(newNode);

                ++size;

                if (size <= capacity)
                {
                    return;
                }

                // pop the tail
                var popTail = PopTail();
                cache.Remove(popTail.Key);
                --size;
            }
            else
            {
                // update the value.
                node.Value = value;
                MoveToHead(node);
            }
        }
Example #3
0
        private static void RemoveNode(DLinkedNode node)
        {
            DLinkedNode prev = node.Prev;
            DLinkedNode next = node.Next;

            prev.Next = next;
            next.Prev = prev;
        }
Example #4
0
        private void AddNode(DLinkedNode node)
        {
            // add new one, next to head
            node.Prev = head;
            node.Next = head.Next;

            head.Next.Prev = node;
            head.Next      = node;
        }
Example #5
0
        public int Get(int key)
        {
            DLinkedNode node = cache[key];

            if (node == null)
            {
                return(-1);
            }

            // move the accessed node to the head;
            MoveToHead(node);

            return(node.Value);
        }
Example #6
0
        public LRUCache(int capacity)
        {
            this.size     = 0;
            this.capacity = capacity;

            head = new DLinkedNode();
            // head.prev = null;

            tail = new DLinkedNode();
            // tail.next = null;

            head.Next = tail;
            tail.Prev = head;
        }
Example #7
0
 private void MoveToHead(DLinkedNode node)
 {
     RemoveNode(node);
     AddNode(node);
 }