C语言链表查找字符串 - 跨节点匹配
以下是实现该功能的C代码:\n\nc\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct list_s {\n char *data;\n struct list_s *next;\n} list_t;\n\nint find_list_str(list_t *list, char *str) {\n while (list != NULL) {\n // 检查当前节点的data是否包含目标字符串\n if (strstr(list->data, str) != NULL) {\n return 1; // 存在\n }\n \n // 检查当前节点的结尾和下一个节点的开头是否组成目标字符串\n int str_len = strlen(str);\n int node_data_len = strlen(list->data);\n if (node_data_len >= str_len) {\n char *next_node_start = list->data + node_data_len - str_len + 1;\n if (list->next != NULL && strncmp(next_node_start, str, str_len - 1) == 0) {\n return 1; // 存在\n }\n }\n \n list = list->next; // 移动到下一个节点\n }\n \n return 0; // 不存在\n}\n\nint main() {\n // 创建链表\n list_t *list = (list_t *)malloc(sizeof(list_t));\n list->data = "Hello";\n list->next = (list_t *)malloc(sizeof(list_t));\n list->next->data = "World";\n list->next->next = NULL;\n \n // 在链表中查找字符串\n char *str = "low";\n int result = find_list_str(list, str);\n \n // 输出结果\n if (result) {\n printf("字符串 \"%s\" 存在于链表中\n", str);\n } else {\n printf("字符串 \"%s\" 不存在于链表中\n", str);\n }\n \n // 释放链表内存\n list_t *current = list;\n while (current != NULL) {\n list_t *next = current->next;\n free(current);\n current = next;\n }\n \n return 0;\n}\n\n\n该代码首先定义了一个list_t结构体,包含一个char *类型的data成员和一个指向下一个节点的指针next。\n\nfind_list_str函数用于在链表中查找目标字符串。它使用while循环遍历链表的每个节点,首先检查当前节点的data成员是否包含目标字符串,如果是,则返回1表示存在。\n\n然后,它检查当前节点的结尾和下一个节点的开头是否组成目标字符串。这里使用strstr函数来判断当前节点的结尾是否包含目标字符串的一部分,如果是,则返回1表示存在。\n\n最后,如果遍历完整个链表仍然没有找到目标字符串,则返回0表示不存在。\n\n在main函数中,我们创建了一个简单的链表,并调用find_list_str函数来查找字符串"low"。根据查找结果,打印相应的输出。\n\n最后,我们释放了链表所占用的内存,避免内存泄漏。
原文地址: https://www.cveoy.top/t/topic/pKeF 著作权归作者所有。请勿转载和采集!