Esempio n. 1
0
        public void Put(int key, int value)
        {
            int index = Hash(key);

            if (dic[index] == null)
            {
                Node1 newnode = new Node1(key, value);
                dic[index] = newnode;
                itemCount++;
                AddToHeader(newnode);

                if (itemCount > capacity)
                {
                    dic[tail.prev.key] = null;
                    RemoveNode(tail.prev);
                }
            }
            else
            {
                Node1 n = dic[index];
                n.value = value;
                RemoveNode(n);
                AddToHeader(n);
            }


            //RemoveNode(prev.next);
            //AddToHeader(prev.next);
        }
Esempio n. 2
0
 private void AddToHeader(Node1 node)
 {
     node.next      = header.next;
     node.next.prev = node;
     node.prev      = header;
     header.next    = node;
 }
Esempio n. 3
0
 public LRUCache4(int capacity)
 {
     dic           = new Node1[1001];
     this.capacity = capacity;
     header        = new Node1(-1, -1);
     tail          = new Node1(-1, -1);
     header.next   = tail;
     tail.prev     = header;
 }
Esempio n. 4
0
        private Node1 Find(Node1 node, int key)
        {
            Node1 n    = node;
            Node1 prev = null;

            while (n != null && n.key != key)
            {
                prev = n;
                n    = n.next;
            }
            return(prev);
        }
Esempio n. 5
0
        public int Get(int key)
        {
            int index = Hash(key);

            if (dic[index] == null)
            {
                return(-1);
            }
            Node1 n      = dic[index];
            int   result = n.value;

            RemoveNode(n);
            AddToHeader(n);

            return(result);
        }
Esempio n. 6
0
 private void RemoveNode(Node1 node)
 {
     node.prev.next = node.next;
     node.next.prev = node.prev;
 }