I need to loop through a vector of linked list and check if a node with the string(s) exists. Obviously this only checks the beginning to see if it exists. I want to know how to go through the entire linked list.
vector <Dlist *> table; //Dlist is the linked list
int DL_Hash::Present(string &s) {
int index = djb_hash(s) % table.size();
for(int i = 0; i < table[index]->Size(); i++) {
if(table[index]->Begin()->s == s) {
return 1;
}
}
return 0;
}
You are not using variable i
at all, and you indeed cant do something like table[index][i]
, as you cant index linked list. You only can get first element in list, and immediate next.
First you get pointer to the beginning (iterator would be more fitting). Then check every item for your condition, until you are at the end of list.
int DL_Hash::Present(string &s) {
int index = djb_hash(s) % table.size();
auto tmp = table[index]->Begin();
while (tmp != nullptr) { // check if you are at end of linked list
if (tmp->s == s)
return 1;
tmp = tmp.Next(); // asuming you have function to get next element in linked list.
}
return 0;
}
If Dlist
would have iterators:
int DL_Hash::Present(string &s) {
int index = djb_hash(s) % table.size();
auto tmp = table[index]->begin();
while (tmp != table[index].end()) { // check if you are at end of linked list
if (tmp->s == s)
return 1;
tmp++;
}
return 0;
}
Or even better, using range for
int DL_Hash::Present(string &s) {
int index = djb_hash(s) % table.size();
for (auto &tmp : table[index]) {
if (tmp->s == s)
return 1;
}
return 0;
}