昨天有考试...结果回寝室就已经半夜了,根本来不及学习很多东西,看了眼散列冲突的拉链法和线性探查法,敲了一点代码报错,头疼就睡了。今天补上。
首先这里有个勘误,之前的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', 'gandalf@email.com')
hashmap.put('Tyrion', 'tyrion@email.com')
hashmap.put('Aaron', 'Aaron@email.com')
hashmap.put('Donnie', 'Donnie@email.com')
hashmap.put('Ana', 'Ana@email.com')
hashmap.put('Jonathan', 'Jonathan@email.com')
hashmap.put('Jamie', 'Jamie@email.com')
hashmap.put('Sue', 'Sue@email.com')
hashmap.remove('Jamie')
let temp = hashmap.get('Jonathan')
console.log('====');
console.log(temp);