使用头指针数组的C++哈希表.如何将我的addNode()私有方法分配给我的头指针键位置



我以前使用指向链表(独立类(对象的指针数组构建了一个哈希表,现在我正尝试使用调用自己链表私有方法的头指针数组构建一个哈希表格。调用私有链表方法不是问题。将它们分配到头部指针数组中的关键位置是我陷入困境的地方。

在不添加整个代码的情况下,这里是我的基本hashtable.h文件:

#define HASHTABLESIZE 15;
class Hashtable {
public:
Hashtable();
bool addEntry(int, string);
private:
int hash(id);
Node *head;
bool addNode(int, string);
}

这是我的hashtable.cpp文件:

Hashtable::Hashtable() {
this->head = new Node[HASHTABLESIZE];
}
int Hashtable::hash(int id) {
if (id > 0) {
return id % HASHTABLESIZE;
}
}
bool Hashtable::addEntry(int id, string stringInfo) {
bool inserted = false;
int position = hash(id);
if (id > 0 && stringInfo != "") {
head[position] = addNode(id, stringInfo); // I know this doesn't work (this is where I am stuck)
inserted = true;
}
}
bool Hashtable::addNode(int id, string stringInfo) {
bool addedNode = false;
if (id > 0 && stringInfo != "") {
Node *newNode = new Node;
Node *current = head;
newNode->prev = NULL;
newNode->next = NULL;
if (head != NULL) {
...
...
...
}
}
}

有了linkedlist类,我只能head[position].addNode(id, "string"),但在它自己的类中,我不知道如何分配特定的键,并调用私有方法,只将值分配给头指针数组中相应的索引。感谢您的帮助。

希望它能起作用。如果没有,它至少会给你一些方向。

Hashtable::Hashtable()
{
//make a new array of Node pointers
//why not instances of Nodes, this makes it easier, as you see later.
this->head = new Node*[HASHTABLESIZE];
for (int i = 0; i < HASHTABLESIZE; i++){
head[i] = nullptr; //set each equal to a nullptr
}
}
int Hashtable::hash(int id)
{
if (id > 0)
{
return id % HASHTABLESIZE;
}
}
bool Hashtable::addEntry(int id, string stringInfo)
{
bool inserted = false;
int position = hash(id);
if (id > 0 && stringInfo != "")
{
addNode(head[position], id, stringInfo); //basically we add a new Node to the Node that was put in.
inserted = true;
}
}
//we have to be able to actually change the pointer value, thus we give it a reference to a pointer.
bool Hashtable::addNode(Node *&toAddTo, int id, string stringInfo)
{
//new node
Node *toAdd = new Node();
//Dont know your Node struct, so just assuming
toAdd->value = stringInfo;
toAdd->id = id;
//next node is nullptr, so if you're later iterating through this list you know when you've hit the end.
toAdd->next = nullptr;
//heres why it's easier to have a list of pointers
if (toAddTo != nullptr){
//make them point to each other.
toAddTo->next = toAdd;
toAdd->prev = toAddTo;
} else {
toAdd->prev = nullptr //same as why next is a nullptr
}
//now the head at that position will be pointing to the last element you put in
toAddTo = toAdd;
return true;
}

最新更新