使用javaScript实现散列表的线性探查法
Posted 等不了
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用javaScript实现散列表的线性探查法相关的知识,希望对你有一定的参考价值。
class ValuePair{ constructor(key,value){ this.key = key; this.value = value; } } function defaultToString(item){ if(item == null){ return ‘null‘; } if(item == undefined){ return ‘undefined‘; } if(typeof item ==‘string‘ || item instanceof String){ return `${item}`; } return item.toString(); } class LinearExploration{ constructor(toStrFn = defaultToString){ this.toStrFn = toStrFn; this.table = {}; } hashCode(key){ return this.loseloseHashCode(key); } loseloseHashCode(key){ if(typeof key == ‘number‘){ return key; } let str = this.toStrFn(key); let addr = 0; for(let i = 0; i < str.length; i++){ addr += str.charCodeAt(i); } return addr; } put(key,value){ if(key != null && value != null){ let position = this.hashCode(key); if(this.table[position]==null){ this.table[position] = new ValuePair(key,value); return true; } //从下一个位置开始 let index = position+1; //寻找空余位置 while(this.table[index]!=null){ index++; } this.table[index] = new ValuePair(key,value); return true; } return ‘undefine‘; } get(key){ let position =this.hashCode(key); if(this.table[position].key === key){ return this.table[position].value; } let index = position+1; while(this.table[index]!=null && this.table[index].key != key){ index++; } if(this.table[index] != null && this.table[index].key === key){ return this.table[index].value; } } remove(key){ const position = this.hashCode(key); if(this.table[position]!=null){ if(this.table[position].key === key){ delete this.table[position]; this.verifyRemoveSideEffect(key,position); return true; } let index = position+1; while(this.table[index] != null && this.table[index].key != key){ index++; } if(this.table[index] != null && this.table[index].key === key){ delete this.table[index]; this.verifyRemoveSideEffect(key,index); return true; } } return false; } verifyRemoveSideEffect(key,removedPosition){ const hash = this.hash(key); let index = removedPosition+1; while(this.table[index] != null){ let posHash = this.hashCode(index); if(posHash <= hash || posHash < removedPosition){ this.table[removedPosition] = this.table[index]; delete this.table[index]; removedPosition = index; } index++; } } }
以上是关于使用javaScript实现散列表的线性探查法的主要内容,如果未能解决你的问题,请参考以下文章