zoukankan      html  css  js  c++  java
  • JavaScript解决哈希表的冲突(分离链接法)

    处理散列表中冲突的方法有:分离链接线性探查双散列法

    分离链接法:为散列表的每一个位置创建一个链表并将元素存储到里面。

    相对于之前的散列表只需重写put、get和remove方法。

        put(key, value) {
            if (key == null || value == null) {  //键值无效
                return false;
            } else {
                let position = hashCode(key);    //转换成编码
                if (this.table[position] == null) {    //判断是位置上是否有链表
                    this.table[position] = new LinkedList(); //没有就创建一个链表
                }
                this.table[position].push(new ValuePair(key, value)); //有链表就在链表上添加元素
                return true;
            }
    
        }
        get(key) {
            let position = this.hashCode(key);    //转换成编码
            let linkedList = this.table[position];  //获取链表
            if (linkedList != null && !linkedList.isEmpty()) {  //链表有效
                let current = this.getHead();
                while (current != null) {                 //从头指针开始遍历链表
                    if (current.element.key === key) {  //找到键所在的对象
                        return current.element.value;   //返回对象中的值
                    }
                    current = current.next;
                }
            }
            return undefined;
        }
        remove(key) {
            let position = this.hashCode(key);    //先将key转换成编码
            let linkedList = this.table[position];  //找到链表
            if (linkedList != null && !linkedList.isEmpty()) {  //链表有效
                let current = linkedList.getHead();  //从头指针开始遍历链表
                while (current != null) {
                    if (current.element.key === key) {         //找到键所在的对象
                        linkedList.remove(current.element);   //删除对象中的键值对
                        if (linkedList.isEmpty()) {       //如果链表为空,删除链表
                            delete this.table[position];
                        }
                        return true;
                    }
                    current = current.next;
                }
            }
            return false;
    }
  • 相关阅读:
    如何配置MySQL
    软件工程第三次作业
    软件工程第二次作业
    软件工程第一次作业
    Python 【面试总结】
    Vue【你知道吗?】
    Python 【面试强化宝典】
    Python 【基础面试题】
    Vue 【前端面试题】
    Redis 【常识与进阶】
  • 原文地址:https://www.cnblogs.com/WP-WangPin/p/13942577.html
Copyright © 2011-2022 走看看