与链表和书类的哈希表通信

时间:2017-11-12 06:22:16

标签: c++ data-structures hash header

我的HashTable类无法识别Book和Linked List类类中的内容。我将头文件包含在顶部,所以我认为问题出在我的代码中?

我是否正确创建了链接列表数组?我有一个Node结构,可以在链表中创建元素。

这是我的HashTable类的源代码

#include "HashTable.h"
#include "Book.h"
#include "List.h"

using namespace std;

HashTable::HashTable() //constructor
{

    List<Book> Table[SIZE];

    Node *Table[SIZE];


    for(int i=0;i<SIZE;i++)
        {
            Table[i]= new Node;
            Table[i]->title = "empty";
            Table[i]->author="empty";
            Table[i]->price=-1;
            Table[i]->isbn=0;
            Table[i]->linkprevious=NULL;
            Table[i]->linknext=NULL;
        }

}


int HashTable:: hash(string key) const
{
    int index, sum = 0;
        for(int i = 0; i < key.length(); i++)
            sum += (int) key[i]; //summing the ASCII values for each character in the string
        index = sum % SIZE; //dividing the summed ASCII values by 35 && storing remainder as my index
        return index;

}


void HashTable:: insert(Book b)
{
    int index=hash(b.title);

    if(HashTable[index]->title=="empty") //if array element is empty
    {
        Table->name=b.title;
        Table->author=b.author;
        Table->price=b.price;
        Table->isbn=b.isbn;
    }
    else //if array element is take-->make linked list
    {
        Node *ptr = Table[index]; //points at desired index(that hash determined)
        Node *N = new Node;  //allocate space and fill fields with entered data
        N->title=b.title;
        N->author=b.author;
        N->price=b.price;
        N->isbn=b.isbn;
        while(ptr->linknext!=NULL)//traverse ptr to end of linked list
            //(incase there is already a linked list in given index)
        {
            ptr=ptr->linknext;
        }
        ptr->linknext=N;
    }


}

1 个答案:

答案 0 :(得分:0)

构造函数使用相同的变量(Table)名称两次。

HashTable::HashTable() //constructor
{
    List<Book> Table[SIZE];
    Node* Table[SIZE];

我不确定你在想什么 - 也许是这样的:

List<Book> Table[SIZE];

for(int i = 0; i < SIZE; i++) {
    Book* book = Table[i].getFirstNode();
    book->title = "empty";
    // ...
}