示例#1
0
            public void Put(int key, int value)
            {
                if (cache.ContainsKey(key))
                {
                    // update the value.
                    cache[key].value = value;
                    moveToHead(cache[key]);
                }
                else
                {
                    DLinkedNode newNode = new DLinkedNode();
                    newNode.key   = key;
                    newNode.value = value;

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

                    ++size;

                    if (size > capacity)
                    {
                        // pop the tail
                        DLinkedNode tail = popTail();
                        cache.Remove(tail.key);
                        --size;
                    }
                }
            }
示例#2
0
            private DLinkedNode popTail()
            {
                //Pop the current tail.
                DLinkedNode res = tail.prev;

                removeNode(res);
                return(res);
            }
示例#3
0
            private void removeNode(DLinkedNode node)
            {
                // Remove an existing node from the linked list.
                DLinkedNode prev = node.prev;
                DLinkedNode next = node.next;

                prev.next = next;
                next.prev = prev;
            }
示例#4
0
            private void addNode(DLinkedNode node)
            {
                //Always add the new node right after head.
                node.prev = head;
                node.next = head.next;

                head.next.prev = node;
                head.next      = node;
            }
示例#5
0
            public int Get(int key)
            {
                if (!cache.ContainsKey(key))
                {
                    return(-1);
                }

                DLinkedNode node = cache[key];

                moveToHead(node);
                return(node.value);
            }
示例#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;
            }
示例#7
0
 private void moveToHead(DLinkedNode node)
 {
     // Move certain node in between to the head.
     removeNode(node);
     addNode(node);
 }