I intend to create a hash table of arrays with concatenated lists as elements.The purpose this time is to create a function that adds data to the hash table with addItem and returns the contents of the hash table with displayTable.If you run this program, you will not get a zero and the program will stop.After many attempts, I think the problem is probably while loop or Link*temp=array[i]->getHead() in the displayTable method.Thank you for your understanding.
HashList.h
#include<iostream>
# include <sstream>
using std::string;
class Link
{
private:
US>string value;
Link*next;
public:
Link(string value, Link*next=nullptr) {this->value=value;next=nullptr;}
~Link(){}
US>string getValue() {return value;}
Link*getNext() {return next;}
void setNext(Link*next) {this->next=next;}
};
class list
{
private:
Link*head;
public:
List() {head=nullptr;}
void addHead(string value)
{
Link*temp = new Link (value, head);
temp->getNext();
head = temp;
}
Link*getHead() {returnhead;}
};
class HashList {
private:
intarraySize;
List**array;
public:
HashList(){
arraySize = 7;
array=newList*[arraySize];
for (inti=0; i<arraySize;i++)
{
array[i] = new List;
}
}
HashList (int size)
{
if (size <7)
{
size = 7;
}
arraySize = size;
array=newList*[arraySize];
for (inti=0; i<arraySize;i++)
{
array[i] = new List;
}
}
int hash (string value)
{
int hashValue = 0;
// figure out the index
for (inti=0; i<value.length(); i++)
{
hashValue*=128;
hashValue+=value[i];
hashValue% = arraySize;
}
// return the index
return hashValue;
}
void addItem(string value)
{
array [hash(value)] - > addHead(value);
}
US>string displayTable()
{
std::stringstreams;
string output;
for (inti=0; i<arraySize;i++)
{
Link*temp=array[i]->getHead();
if(temp==nullptr)
{
ss<<"_empty_";
}
while(temp!=nullptr)
{
ss<<temp->getValue()<
temp=temp->getNext();
}
ss<<"\n";
}
output =ss.str();
return output;
}
};
main.cpp
#include<iostream>
# include "HashList.h"
using namespace std;
int main() {
HashList test;
test.addItem("Hello");
test.addItem("Hello");
cout<<test.displayTable()<endl;
return 0;
}
Link(string value, Link*next=nullptr) {this->value=value;next=nullptr;}
The next=nullptr
here is meaningless.You wanted to do this :
Link(string value, Link*next=nullptr) {this->value=value;this->next=next;}
© 2024 OneMinuteCode. All rights reserved.