简单的Hash Table 实现,下次被问到,至少不是从0开始。不过笔试问这个毕竟不多。

    public struct Item<K, V>
    {
        public K Key { get; set; }

        public V Value { get; set; }
    }

    public class SimpleHashTable<K, V>
    {
        private int _size;

        private LinkedList<Item<K, V>>[] _items;

        public SimpleHashTable(int size)
        {
            this._size = size;
            _items = new LinkedList<Item<K, V>>[_size];
        }

        public void Add(K key, V value)
        {
            var item = Find(key);
            if (item == null)
            {
                var list = FindListByKey(key);
                list.AddLast(new Item<K, V>()
                {
                    Key = key,
                    Value = value
                });
            }
            else
            {
                throw new Exception("The item is already exist.");
            }
        }

        public V Find(K key)
        {
            var list = FindListByKey(key);
            foreach (var item in list)
            {
                if (item.Key.Equals(key))
                {
                    return item.Value;
                }
            }

            return default(V);
        }

        public void Remove(K key)
        {
            var list = FindListByKey(key);
            var item = list.Where(a => a.Key.Equals(key)).FirstOrDefault();
            if (!item.Equals(default(Item<K, V>)))
            {
                list.Remove(item);
            }
        }

        private LinkedList<Item<K, V>> FindListByKey(K key)
        {
            var hash = key.GetHashCode();
            var index = Math.Abs(hash % _size);

            if (_items[index] == null)
            {
                _items[index] = new LinkedList<Item<K, V>>();
            }

            return _items[index];
        }
    }
05-01 22:23