数据结构-如何在javascript中实现哈希表(包括关联列表)

data structure - how to implement hash tables (including association lists) in javascript?

本文关键字:哈希表 包括 关联 列表 实现 javascript 数据结构      更新时间:2023-09-26

我正在做一个哈希表/数据结构练习,但不太理解。每个数据都必须是列表"list"的一个实例,使用哈希函数,我需要将键/值对添加到正确的列表中,并根据它们的键返回项。到目前为止,我所做的一切都不起作用,如果能给我任何帮助或解释我所做一切都不奏效,我将不胜感激!非常感谢。

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];
};

问题很简单,您的错误就在这里:

this.data[index].set({key:key, value:value});

需要更改为

this.data[index].set(key, value);

在您的HashT.prototype.get中,return语句需要是:

return this.data[index].get(key);