12 【HashMap】js 利用分离链接(拉链法)解决散列冲突问题

昨天有考试...结果回寝室就已经半夜了,根本来不及学习很多东西,看了眼散列冲突的拉链法和线性探查法,敲了一点代码报错,头疼就睡了。今天补上。

首先这里有个勘误,之前的linkedlist(链表),不影响链表使用,但影响调用,修改如下:

  // 原来的代码

  // 获取头文件
  getHead () {
    return this.head.element
  }

这里的getHead 方法不应该获取head 的element ,这会导致调用时无法获取head节点,权限变低,修改为:

  // 现在的代码

  // 获取头文件
  getHead () {
    return this.head
  }

做完这些,就可以利用拉链法解决散列冲突问题了。

注:拉链法本质是在hashmap 中插入链表。

'use strict';

let linkedList = require('./linkedlist.js')

// 内部类,定义链表节点内容
class valuePire {
    constructor (key, value) {
        this.key = key;
        this.value = value
    
        this.toString = function () {
            return '[ k:' + this.key + 'value: ' + this.value + ']'
        }
    } 
}
class HashMap {
    constructor () {
        this.table = []
    }
    // 散列函数
    loseloseHashCode (key) {
        let hash = 0;
        for(let i = 0; i < key.length; i++) {
            hash += key[i].charCodeAt()
        }
        return hash % 37
    }


    // 存放
    put (key, value) {
        let position = this.loseloseHashCode(key)

        if (this.table[position] == undefined) {
            this.table[position] = new linkedList()
        }
        this.table[position].append(new valuePire (key, value))
        return 'ok'
    }

    remove (key) {
        let position = this.loseloseHashCode(key)

        if (this.table[position] !== undefined) {
            let current = this.table[position].getHead()
            let previous = current

            while (current) {
                if (current.element.key === key) {
                    previous.next = current.next
                    current.next = null
                    return true
                }
                previous = current
                current = current.next
            }
        }
        return undefined
    }

    get (key) {
        let position = this.loseloseHashCode(key)

        if (this.table[position] !== undefined) {
            // 先拿到链表的头节点
            let current = this.table[position].getHead()
            while (current) {
                if (current.element.key === key) {
                    return current.element.value
                }
                    current = current.next
            }
        }
        return undefined
    }
}

let hashmap = new HashMap();
hashmap.put('Gandalf', '[email protected]')

hashmap.put('Tyrion', '[email protected]')
hashmap.put('Aaron', '[email protected]')

hashmap.put('Donnie', '[email protected]')
hashmap.put('Ana', '[email protected]')

hashmap.put('Jonathan', '[email protected]')
hashmap.put('Jamie', '[email protected]')
hashmap.put('Sue', '[email protected]')
hashmap.remove('Jamie')
let temp = hashmap.get('Jonathan')
console.log('====');
console.log(temp);

你可能感兴趣的:(12 【HashMap】js 利用分离链接(拉链法)解决散列冲突问题)