示例#1
0
        private void RemoveNode(LinkedNode toRemove)
        {
            // remove current one and relink
            var prev = toRemove.Prev;
            var next = toRemove.Next;

            prev.Next = next;
            next.Prev = prev;
        }
示例#2
0
        private void MoveToHead(LinkedNode first)
        {
            // move to head
            var second = Head.Next;

            Head.Next   = first;
            first.Prev  = Head;
            first.Next  = second;
            second.Prev = first;
        }
示例#3
0
        public void Put(int key, int value)
        {
            if (Dictionary.TryGetValue(key, out var node))
            {
                RemoveNode(node);
                MoveToHead(node);
                node.Val = value;
            }
            else
            {
                if (Dictionary.Count == Capacity)
                {
                    var last = Tail.Prev;
                    RemoveNode(last);
                    Dictionary.Remove(last.Key);
                }

                var newNode = new LinkedNode {
                    Key = key, Val = value
                };
                MoveToHead(newNode);
                Dictionary[key] = newNode;
            }
        }