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;
}

 

posted @ 2020-11-07 21:52  WP-WangPin  阅读(176)  评论(0编辑  收藏  举报