[英]data structure - how to implement hash tables (including association lists) in javascript?
I am working on a hash table /data structure exercise but dont understand it quite well. 我正在做哈希表/数据结构练习,但不太了解。 Each data has to be an instance of the list 'List' and using athe hash function, I need to add key /value pairs to the correct list and return the items based on their key.
每个数据都必须是列表“列表”的实例,并使用哈希函数,我需要将键/值对添加到正确的列表中,并根据其键返回项目。 As what I tried so far doesnt work, any help or explanation why what I have so far doesnt work would be much appreciated!
由于我到目前为止所做的尝试行不通,因此,请多多关照我为何到目前为止所做的任何帮助或解释! Thank you!
谢谢!
function List () {
this.head=null;
}
function ListN (key, value, next) {
this.key = key;
this.value = value;
this.next = next;
}
List.prototype.set = function (key, value) {
var newNode=new ListN(key, value, this.head);
this.head=newNode;
};
List.prototype.get = function (key) {
var node = this.head;
while (node) {
if (node.key === key) {
return node.value;
}
node = node.next;
}
};
smallList = new List();
function HashT () {
this.data = Array(30);
}
HashT.prototype.set = function (key, value) {
var index=hash(key);
if (!this.data[index]) {
this.data[index]=new List();
}
this.data[index].set({key:key, value:value});
};
HashT.prototype.get = function (key) {
var index=hash(key);
return this.data[index];
};
The problem is simple, your mistake is here: 问题很简单,您的错误在这里:
this.data[index].set({key:key, value:value});
It needs to be changed to 它需要更改为
this.data[index].set(key, value);
In your HashT.prototype.get
, the return
statement needs to be: 在您的
HashT.prototype.get
, return
语句需要为:
return this.data[index].get(key);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.