c - 测试 LinkedList 中是否存在字符串

标签 c linked-list

我对 LinkedList 的经验很少,无法弄清楚测试字符串是否位于其中一个节点的逻辑。该程序总体上等待客户端发送 DNS 查询,然后以无限循环发回响应。我想做的是:

确定 LinkedList 是否具有客户端请求的主机名。如果不存在,请将其添加到 LinkedList 中,并在执行查找后将答案保存到同一节点。如果存在,只需向客户提供我已经查找并存储在 answer[] 中的答案即可。

这是一段简化的代码:

struct queryCache {
    char* hostName;
    uint8_t answer[UDP_RECV_SIZE];
    struct queryCache* next;
};
struct queryCache* qcRoot;

int main (int argc, char** argv) {
    // ...unrelated code

    qcRoot = malloc(sizeof(struct queryCache));
    qcRoot->hostName = 0;
    qcRoot->next = 0;

    while (1) {
        // Wait for client with recvfrom()

        char* cqHostName;
        // Code that malloc()s and strcpy()s the client hostname into cqHostName

        // Determine if cqHostName is in the cache
        int hostNameInCache = 0;
        struct queryCache* currQC = qcRoot;
        while (currQC) {
            if (!strcmp(currQC->hostName, cqHostName)) {
                puts("In the cache");
                hostNameInCache = 1;
                break;
            }
            currQC = currQC->next;
        }

        // If cqHostName is not in the cache add its name
        if (!hostNameInCache) {
            currQC->hostName = malloc(strlen(cqHostName)+1);
            strcpy(currQC->hostName, cqHostName);
            printf("Added HOSTNAME: %s to the cache\n", cqHostName);

            currQC->next = malloc(sizeof(struct queryCache));
            currQC = currQC->next;
            currQC->hostName = 0;
            currQC->next = 0;
        }

        // Code that does a recursive DNS

        // Code that will copy the response into the appropriate answer[] of the LinkedList
    }
}

该程序似乎只是在第一个客户端请求后退出,而没有给出错误。如果我删除 LinkedList 代码,它就可以正常工作,所以我很确定出了什么问题与我检查字符串是否在 LinkedList 中的方式有​​关。

最佳答案

hostNameInCache为0时,currQC很可能为NULL,因此您无法推迟它。

将 while 循环的条件更改为

#------------v
while (currQC->next) {
    if (!strcmp(currQC->hostName, cqHostName)) {
            puts("In the cache");
            hostNameInCache = 1;
            break;
        }
        currQC = currQC->next;
}

关于c - 测试 LinkedList 中是否存在字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19535019/

相关文章:

java - 如何仅使用 O(1) 空间在链表上实现归并排序?

c++ - 需要调试在docker中运行的混合 "C and C++"代码

c - 井字游戏 AI 错误

c++ - 存储和检索 char 数组的地址/指针

java - 链表删除错误

c++ - 关于如何实现的想法?

常量指针数组还是指向数组的指针? C中什么更快?

c - 结构节点释放

c - 有没有办法在C中获得模板效果?

c - 如何在链表中将节点从头移动到尾? C