C#数据结构与算法学习笔记 哈希表

1.哈希函数的设计




    class Program
    {
        static void Main(string[] args)
        {
            int a = 123;
            Console.WriteLine(a.GetHashCode());

            int b = -123;
            Console.WriteLine(b.GetHashCode());

            float c = 0.5f;
            Console.WriteLine(c.GetHashCode());

            string d = "abc";
            Console.WriteLine(d.GetHashCode());

            Console.Read();
        }
    }

2.哈希冲突处理



基于拉链法的顺序查找哈希表:

    class HashST1<Key>
    {
        private LinkedList1<Key>[] hashtable;   //每个位置都指向一条链表,将冲突的元素都存在链表中
        private int M;
        private int N;

        public HashST1(int M)
        {
            this.M = M;
            N = 0;
            hashtable = new LinkedList1<Key>[M];
            for (int i = 0; i < M; i++)
                hashtable[i] = new LinkedList1<Key>();
        }

        public HashST1() : this(97) { }

        public int Count { get { return N; } }

        public bool IsEmpty { get { return N == 0; } }

        //将键转化为数组的索引
        private int Hash(Key key)
        {
            return (key.GetHashCode() & 0x7fffffff) % M;
        }
    }

3.哈希表添加、删除、包含

        public void Add(Key key)
        {
            LinkedList1<Key> list = hashtable[Hash(key)];
            if (list.Contains(key))
                return;
            else
            {
                list.AddFirst(key);
                N++;
            }
        }

        public void Remove(Key key)
        {
            LinkedList1<Key> list = hashtable[Hash(key)];
            if (list.Contains(key))
            {
                list.Remove(key);
                N--;
            } 
        }

        public bool Contains(Key key)
        {
            LinkedList1<Key> list = hashtable[Hash(key)];
            return list.Contains(key);
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值