gpt4 book ai didi

c++ - 遍历链表以查找字符串

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:38 26 4
gpt4 key购买 nike

我需要遍历链表 vector 并检查是否存在具有字符串的节点。显然,这只会检查开头以查看它是否存在。我想知道如何遍历整个链表。

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

最佳答案

你根本没有使用变量 i,你确实不能做像 table[index][i] 这样的事情,因为你不能索引链表。您只能获取列表中的第一个元素,紧随其后。

首先你得到指向开始的指针(迭代器会更合适)。然后根据您的情况检查每个项目,直到您位于列表的末尾。

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

如果 Dlist 有迭代器:

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

或者更好的是,使用 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;
}

关于c++ - 遍历链表以查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49642174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com