0
点赞
收藏
分享

微信扫一扫

数据结构:散列表【源码】


文章目录

  • ​​散列函数​​


之前学过数据结构:栈、队列,链表和字典。

散列函数

实现尽可能快地在数据结构中找到一个值,以前想查询数据结构中的一个值的时候,是需要迭代整个数据结构的。

散列函数的作用是给定一个值,然后返回改的在表中的地址。

在散列函数中,我们首先需要检验一个key是否是一个数字,如果是,则返回key;反之,根据key的每一个字符的ASCII码的总和。

loseloseHashCode(key) {
if (typeof key === 'number') {
return key;
}

const tableKey = this.toStrFn(key);
let hash = 0;

for (let index = 0; index < tableKey.length; index++) {
hash += tableKey.charCodeAt(index)
}

return hash % 37;
}

最后将总和与任意一个数做除法取余,这样可以避免操作数超过变量最大表示范围的风险。

/**
* 散列算法:尽可能块的在数据结构中找到一个值
*/
function defaultToString(items) {
if (items === null) {
return "NULL";
} else if (items === undefined) {
return "UNDEFINED";
} else if (typeof items === 'string' || items instanceof String) {
return `${items}`;
}

return items.toString();
}

class ValuePair {
constructor(key,) {
this.key = key;
this.value = value;
}

toString() {
return `[#${this.key}:${this.value}]`;
}
}

class HashTable {
constructor(toStrFn =) {
this.toStrFn = toStrFn;
this.table = {};
}

put(key,) {
if (key != null && value != null) {
const postion = this.hashCode(key);
this.table[postion] = new ValuePair(key, value);
return true
}
return false;
}
remove(key) {
const hash = this.hashCode(key);
const valuePair = this.table[hash];
if (valuePair != null) {
delete this.table[hash];
return true
}

return false;
}
get(key) {
const valuePair = this.table[this.hashCode(key)];

return valuePair == null ? undefined : valuePair.value;
}

loseloseHashCode(key) {
if (typeof key === 'number') {
return key;
}

const tableKey = this.toStrFn(key);
let hash = 0;

for (let index = 0; index < tableKey.length; index++) {
hash += tableKey.charCodeAt(index)
}

return hash % 37;
}

hashCode(key) {
return this.loseloseHashCode(key)
}
}


const hash = new HashTable();
hash.put("duXin", "");
hash.put("xueLian", ");
hash.put("qingZhuYue", );

console.log(hash.hashCode("xueLian"))


举报

相关推荐

0 条评论