public void Put(int key, int value)
        {
            int oldValue = Get(key);

            if (oldValue == -1)
            {
                if (_linkedList.Count + 1 > _capacity)
                {
                    var tail      = _linkedList.Last;
                    int removeKey = tail.Value.Key;
                    _hash.Remove(removeKey);
                    _linkedList.RemoveLast();
                }

                // add as new head
                CacheData data = new CacheData(key, value);
                _linkedList.AddFirst(new LinkedListNode <CacheData>(data));

                var head = _linkedList.First;
                _hash.Add(key, head);
            }
            // key exist but value is not the same. update key
            else
            {
                _hash[key].Value.Value = value;
            }
        }
Exemple #2
0
        public T Pop()
        {
            if (List.Count <= 0)
            {
                throw new Exception("Unable to pop item. Stack is empty.");
            }

            T topItem = List.Last.Value;

            List.RemoveLast();
            return(topItem);
        }
        /// <inheritdoc/>
        /// <exception cref="InvalidOperationException">The key is already added.</exception>
        public void AddToBottom(K key, V value)
        {
            var valueContainer = list.AddLast(new Pair <K, V>(key, value));

            try {
                map.Add(key, valueContainer);
            }
            catch (Exception e) {
                list.RemoveLast();
                if (e is ArgumentException)
                {
                    throw new InvalidOperationException(Strings.ExCollectionAlreadyContainsItemWithSpecifiedKey);
                }
                else
                {
                    throw;
                }
            }
        }
        public void Set(int key, int value)
        {
            if (Get(key) != -1)
            {
                LinkedListNode <int> node = _values[key];
                node.Value = value;
            }
            else
            {
                if (_linkedList.Count + 1 > _capacity)
                {
                    var lastKey = _values.FirstOrDefault(x => x.Value.Equals(_linkedList.Last)).Key;
                    if (lastKey > 0)
                    {
                        _values.Remove(lastKey);
                    }

                    _linkedList.RemoveLast();
                }

                LinkedListNode <int> node = _linkedList.AddFirst(value);
                _values.Add(key, node);
            }
        }
 public void RemoveLast() => linkedList.RemoveLast();